var jsonRequestData = {
    form_id: "1",
    search_value: "",
    field: "0",
    start: "0",
    date_field: "",
    date_from: "",
    date_to: "",
    "column-sort": "",
    "column-sort-type": "",
}

function removeDuplicates(arrayIn) {
    var arrayOut = [];
    for (var a = 0; a < arrayIn.length; a++) {
        if (arrayOut[arrayOut.length - 1] != arrayIn[a]) {
            arrayOut.push(arrayIn[a]);
        }
    }
    return arrayOut;
}
$(document).ready(function() {

    var pathname = window.location.pathname;
    if (pathname == "/user_view/workspace") {
        AutoCompletePicklist.init();
        initializePage.init();
    }

    // Check All Application
    $("body").on("click", ".appCheckAll", function() {
        var formName = $(this).attr("data-type-form-name");

        if ($(this).is(':checked')) {
            var parse_button = {};
            var workflow_id = "";
            var form_name = "";
            $("." + formName).each(function() {
                var buttons = $(this).attr("button-action-data");
                workflow_id = $(this).attr("button-workflow-id");
                form_class = $(this).attr("class");
				form_name = $(this).attr("data-form-name");
                if (buttons != "") {

                    //parse_button = JSON.parse(buttons);
                    $.extend(parse_button, JSON.parse(buttons));

                    $(this).attr("checked", true);
                }
            });

            // Buttons
            var btns = "";
            for (button_request in parse_button) {
                //console.log(parse_button[button_request])
                var form_id = $("#form_id").val();
                var btn_name = parse_button[button_request].button_name;
                var btn_action = parse_button[button_request].child_id;
                btns += '<option class="' + form_class + '" data-form-name="' + form_name + '" value="' + btn_name + '" form-id="' + form_id + '" data-workflow-id="' + workflow_id + '" action="' + btn_action + '">' + btn_name + '</option>';
            }
            $("#request_buttons").append(btns);
        } else {
            $("." + formName).each(function() {
                $(this).attr("checked", false);
            });
        }
    });

    $("body").on("change", "#request_buttons", function() {
        var self = $("#request_buttons option:selected");
        var form_name = self.attr("data-form-name");
        var form_id = self.attr("form-id");
        var node_id = self.attr("action");
        var form_request = [];
        var self = this
        jConfirm('Are you sure you want to proceed?', '', '', '', '', function(r) {
            if (r == true) {
                
                $("." + form_name + "[checked=checked]").each(function(id, val) {
                    var request_details = {};
                    var request_id = $(this).attr('button-request-id');
                    var formId = form_id;
                    var workflowId = $(this).attr('button-workflow-id');
                    var nodeId = node_id;
                    ui.block();
        
                    request_details['FormID'] = formId;
                    request_details['ID'] = request_id;
                    request_details['Node_ID'] = nodeId;
                    request_details['Workflow_ID'] = workflowId;
                    request_details['Mode'] = "viewApproval";
        
                    //request_details = {
                    //    FormID: formId,
                    //    ID: request_id,
                    //    Node_ID: nodeId,
                    //    Workflow_ID: workflowId,
                    //    Mode: "viewApproval"
                    //}
        
                    //jConfirm('Are you sure you want to proceed?', '', '', '', '', function(r) {
                    //    if (r) {
                    //        RequestViewSearch.process(request_details);
                    //    }
                    //});
					// console.log(request_id,"test");
                    form_request.push(request_details);
                    console.log(form_request)
                });
				
                $.post('/ajax/requestBulk/', {
                    data: JSON.stringify(form_request)
                }, function(data) {
                    console.log(data)
                    var dashboardItemContainer = ".fl-table-wrapper";
                    var tableID = $(self).closest(dashboardItemContainer).find(".dataTable").attr("id");
                    $(self).closest(dashboardItemContainer).find(".dataTable").dataTable().fnDestroy();
                    GetRequestsDataTable.defaultData(jsonRequestData, self);
                    
                    var btns = '<option value="0">Button Selection</option>';
                    $(".checkAllAction").attr("checked",false);
                    $("#request_buttons").html(btns);
                    ui.unblock();
                });
            }
        });
        
    });
})





var pathname = window.location.pathname;
if (pathname == "/user_view/workspace") {
    var computed = {
        init: function() {
            this.load();
        },
        load: function() {
            var self = this;
            var computedFields = [];
            var computedFieldPost = [];
            $('[data-type="computed"]').find('.getFields').each(function() {
                computedFields.push({
                    FieldName: $(this).attr('name'),
                    ProcessorType: $(this).attr('processor-type'),
                    Processor: $(this).attr('processor')
                });
                computedFieldPost.push($(this).attr('name'));
            });

            $('#computedFields').val(JSON.stringify(computedFieldPost));

            var reference = {
                fields: JSON.stringify(computedFields)
            };
            ui.block();
            this.lookup(reference, function(data) {
                data = JSON.parse(data);
                console.log(data);
                for (var index in data) {
                    $('[name="' + data[index].FieldName + '"]').attr('disabled', false);
                    $('[name="' + data[index].FieldName + '"]').attr('readonly', true);
                    $('[name="' + data[index].FieldName + '"]').val(data[index].Processor);
                }

                ui.unblock();
                embeded_view.init();
            });
        },
        lookup: function(reference, callback) {
            $.get('/ajax/request_computed_fields', reference, function(data) {
                callback(data);
            });
        }
    };
    var embeded_view = {
        init: function() {
            this.load();
        },
        load: function() {
            var self = this;
            $('.embed-view-container').each(function() {
                var formId = $(this).attr('embed-source-form-val-id');
                var fieldReference = $(this).attr('embed-result-field-val');
                var fieldValue = $('[name="' + fieldReference + '"]').val();
                var fieldFilter = $(this).attr('embed-source-lookup-active-field-val');
                var fieldReferenceType = $(this).attr('rfc-choice');

                if (fieldReferenceType == 'computed') {
                    var thisFormula = $(this).attr('embed-computed-formula');
                    var formulaDoc = new Formula(thisFormula);
                    fieldValue = formulaDoc.getEvaluation();
                }

                var container = this;
                if (fieldValue !== '' && fieldValue !== null && fieldValue !== 'null') {
                    var reference = {
                        FormID: formId,
                        FieldReference: fieldReference,
                        FieldValue: fieldValue,
                        FieldFilter: fieldFilter,
                        HLData: "",
                        HLType: "row",
                        HLAllow: "false",
                        column_data: "",
                        current_form_fields_data: []
                    };
                    if (typeof $(container).attr('embed-hl-data') != "undefined") {
                        reference["HLData"] = $(container).attr('embed-hl-data');
                    }
                    if (typeof $(container).attr('allow-highlights') != "undefined") {
                        reference["HLAllow"] = $(container).attr('allow-highlights');
                    }
                    if (typeof $(container).attr('allow-highlights') != "undefined") {
                        reference["HLType"] = $(container).attr('highlight-type');
                    }
                    if (typeof $(container).attr('embed-column-data') != "undefined") {
                        reference["column_data"] = $(container).attr('embed-column-data');
                    }

                    $('#frmrequest').find(".setOBJ").each(function(eqi) {
                        var data_object_id = $(this).attr("data-object-id");
                        var getFIELDS = $(this).find(".getFields_" + data_object_id);
                        var field_name = $(this).find(".getFields_" + data_object_id).eq(0).attr("name");
                        field_name_values = [];
                        getFIELDS.each(function(eqi2) {
                            field_name_values.push($(this).val());
                        })
                        field_name_values = field_name_values.join("|^|");
                        reference["current_form_fields_data"].push({
                            "f_name": field_name,
                            "values": field_name_values
                        })
                    })
                    reference["current_form_fields_data"] = JSON.stringify(reference["current_form_fields_data"]);
                    $(container).html('<center><img src="/images/loader/loader.gif" class="load-app-request" style="display: inline;margin-top:30px;"></center>');
                    self.getRequests(reference, function(data) {
                        $(container).html(data);
                    });
                }

                $('[name="' + fieldReference + '"]').change(function() {
                    fieldValue = $(this).val();
                    reference = {
                        FormID: formId,
                        FieldReferece: fieldReference,
                        FieldValue: fieldValue,
                        FieldFilter: fieldFilter,
                        HLData: "",
                        HLType: "row",
                        HLAllow: "false",
                        column_data: "",
                        current_form_fields_data: []
                    };
                    if (typeof $(container).attr('embed-hl-data') != "undefined") {
                        reference["HLData"] = $(container).attr('embed-hl-data');
                    }
                    if (typeof $(container).attr('allow-highlights') != "undefined") {
                        reference["HLAllow"] = $(container).attr('allow-highlights');
                    }
                    if (typeof $(container).attr('allow-highlights') != "undefined") {
                        reference["HLType"] = $(container).attr('highlight-type');
                    }
                    if (typeof $(container).attr('embed-column-data') != "undefined") {
                        reference["column_data"] = $(container).attr('embed-column-data');
                    }

                    $('#frmrequest').find(".setOBJ").each(function(eqi) {
                        var data_object_id = $(this).attr("data-object-id");
                        var getFIELDS = $(this).find(".getFields_" + data_object_id);
                        var field_name = $(this).find(".getFields_" + data_object_id).eq(0).attr("name");
                        field_name_values = [];
                        getFIELDS.each(function(eqi2) {
                            field_name_values.push($(this).val());
                        })
                        field_name_values = field_name_values.join("|^|");
                        reference["current_form_fields_data"].push({
                            "f_name": field_name,
                            "values": field_name_values
                        })
                    })
                    reference["current_form_fields_data"] = JSON.stringify(reference["current_form_fields_data"]);
                    $(container).html('<center><img src="/images/loader/loader.gif" class="load-app-request" style="display: inline;margin-top:30px;"></center>');
                    self.getRequests(reference, function(data) {
                        console.log(data);
                        $(container).html(data);
                    });
                });
            });
        },
        getRequests: function(reference, callback) {
            $.post('/ajax/embedded_view', reference, function(data) {
                callback(data);
            });
        }
    };

    function checkStaticTablesGAP() {
        function collapseByRow(dis_ele) {
            var collapse_elements = {
                "elem_to_collapse": null,
                "elem_to_expand": null
            };
            var selected_tbody = $(dis_ele).children("tbody").eq(0);
            var selected_trs = selected_tbody.children("tr");
            selected_trs.each(function(eq_trs) {
                var row_total_field_setOBJ = $(this).find(".setOBJ")
                        .filter(function(index, dom_ele) {
                            var looped_ele = $(dom_ele);
                            var data_object_id = looped_ele.attr("data-object-id");
                            var getFields_ele = looped_ele.find("#obj_fields_" + data_object_id);
                            if (getFields_ele.length >= 1) {
                                if (getFields_ele.find('[name]').length >= 1) {
                                    return true;
                                } else {
                                    return false;
                                }
                            } else {
                                return false;//wag iselect
                            }
                        });


                var row_total_field_hidden = $(this).find(".setOBJ")
                        .filter(function(index, dom_ele) {
                            var looped_ele = $(dom_ele);
                            var data_object_id = looped_ele.attr("data-object-id");
                            var getFields_ele = looped_ele.find("#obj_fields_" + data_object_id);
                            if (getFields_ele.length >= 1) {
                                if (getFields_ele.find('[name]').length >= 1) {
                                    if (looped_ele.css("display") == "none") {
                                        return true;
                                    } else {
                                        return false;
                                    }
                                } else {
                                    return false;
                                }
                            } else {
                                return false;//wag iselect
                            }
                        });
                // console.log(eq_trs,"GRAA",row_total_field_setOBJ," === ",row_total_field_hidden);
                if (row_total_field_setOBJ.length >= 1) {
                    if (row_total_field_setOBJ.length == row_total_field_hidden.length) {
                        $(this).children('td').stop(true, true);
                        if ($(this).children('td').css("display") != "none") {
                            $(this).data("rVisibilityHeightTD", $(this).outerHeight());
                            // $(this).children('td').animate({
                            //     "height":0
                            // },function(){
                            //     $(this).css("display","none");
                            // })//ANIMATE
                            $(this).children('td').css({
                                "display": "none"
                            })
                            if (collapse_elements["elem_to_collapse"] != null) {
                                collapse_elements["elem_to_collapse"] = $(collapse_elements["elem_to_collapse"].add($(this).children('td')));
                            } else {
                                collapse_elements["elem_to_collapse"] = $($(this).children('td'));
                            }
                        }
                    } else {
                        if ($(this).data("rVisibilityHeightTD")) {
                            height_rTD = $(this).data("rVisibilityHeightTD");
                            $(this).children('td').css("display", "table-cell");
                            // $(this).children('td').filter(function(index, ele_dom){if($(ele_dom).attr("cvisibilitywidthtd")){return false;}else{return true;} }).stop(true,true).animate({
                            //     "height":height_rTD
                            // },function(){
                            //     $(this).css("display","table-cell");
                            // }) //ANIMATE
                            $(this).children('td').filter(function(index, ele_dom) {
                                if ($(ele_dom).attr("cvisibilitywidthtd")) {
                                    return false;
                                } else {
                                    return true;
                                }
                            }).css({
                                "display": "table-cell"
                            }) //STATIC
                            if (collapse_elements["elem_to_expand"] != null) {
                                collapse_elements["elem_to_expand"] = $(collapse_elements["elem_to_expand"].add($(this).children('td').filter(function(index, ele_dom) {
                                    if ($(ele_dom).attr("cvisibilitywidthtd")) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                })));
                            } else {
                                collapse_elements["elem_to_expand"] = $($(this).children('td').filter(function(index, ele_dom) {
                                    if ($(ele_dom).attr("cvisibilitywidthtd")) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                }));
                            }
                        } else {
                            $(this).children('td').filter(function(index, ele_dom) {
                                if ($(ele_dom).attr("cvisibilitywidthtd")) {
                                    return false;
                                } else {
                                    return true;
                                }
                            }).css("display", "table-cell");

                        }
                    }
                }
            })
            return collapse_elements;
        }
        function collapseByColumn(dis_ele) {//COLUMN BASIS
            var selected_tbody = $(dis_ele).children("tbody").eq(0);
            var selected_trs = selected_tbody.children("tr");
            var total_columns = selected_trs.eq(0).children("td").length;
            for (var ii = 0; ii < total_columns; ii++) {
                var selected_col = $(selected_trs.children("td").eq(ii));
                selected_trs.each(function(eq_trs) {
                    if (eq_trs != 0) {
                        selected_col = selected_col.add($(this).children("td").eq(ii));
                    }
                })


                var col_total_field_hidden = selected_col.find(".setOBJ").filter(function(index, dom_ele) {
                    var looped_ele = $(dom_ele);
                    var data_object_id = looped_ele.attr("data-object-id");
                    var getFields_ele = looped_ele.find("#obj_fields_" + data_object_id);
                    if (getFields_ele.length >= 1) {
                        if (getFields_ele.find('[name]').length >= 1) {
                            if (looped_ele.css("display") == "none") {
                                return true;
                            } else {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    } else {
                        return false;//wag iselect
                    }
                });


                var col_total_field_setOBJ = selected_col.find(".setOBJ").filter(function(index, dom_ele) {
                    var looped_ele = $(dom_ele);
                    var data_object_id = looped_ele.attr("data-object-id");
                    var getFields_ele = looped_ele.find("#obj_fields_" + data_object_id);
                    if (getFields_ele.length >= 1) {
                        if (getFields_ele.find('[name]').length >= 1) {
                            return true;
                        } else {
                            return false;
                        }
                    } else {
                        return false;//wag iselect
                    }
                });

                console.log("COLUMN " + ii + "::", selected_col);
                console.log("COLUMN SETOBJ" + ii + "::", selected_col.find(".setOBJ"));
                if (col_total_field_setOBJ.length == col_total_field_hidden.length) {
                    selected_col.stop(true, true);
                    if (selected_col.css("display") != "none") {
                        selected_col.attr("cVisibilityWidthTD", selected_col.filter(function(index, elem_dom) {
                            if ($(elem_dom).css("display") != "none") {
                                return true;
                            } else {
                                return false;
                            }
                        }).outerWidth());

                        // selected_col.animate({
                        //     "width":0
                        // },function(){
                        //     console.log("NONE",$(this).css("display","none")    )
                        // });//animate
                        selected_col.css("display", "none");
                    }

                    // selected_col.stop(true,true);
                    // if(selected_col.css("display") != "none"){
                    //     $(this).data("rVisibilityHeightTD",$(this).outerHeight());
                    // }
                    // $(this).children('td').animate({
                    //     "height":0
                    // },function(){
                    //     $(this).css("display","none");
                    // })
                } else {
                    // alert(selected_col.css("display"))
                    // console.log("BABA",selected_col);
                    // var showed_ele_td = selected_col.filter(function(index, dom_ele){
                    //     if($(this).css("display") != "none" && !$(this).parents("tr").eq(0).data("rVisibilityHeightTD")){
                    //         return true;
                    //     }else{
                    //         return false;
                    //     }
                    // }).length;


                    // if(showed_ele_td == 0 ){

                    // }else if(showed_ele_td >= 1){
                    //     var load_td_width = selected_col.attr("cVisibilityWidthTD");
                    //     selected_col.css("display","table-cell");
                    // }
                    var showed_ele_td = selected_col.filter(function(index, dom_ele) {
                        if ($(this).css("display") != "none" && !$(this).parents("tr").eq(0).data("rVisibilityHeightTD")) {
                            return true;
                        } else {
                            return false;
                        }
                    }).length;
                    if (showed_ele_td == 0) {
                        var load_td_width = selected_col.attr("cVisibilityWidthTD");
                        selected_col.css("display", "table-cell");
                    }
                }
            }

            // selected_trs.each(function(eq_trs){

            //     var selected_tds = $(this).children("td");
            // })
            return {};
        }
        $(".form-table.thisDynamicTable").each(function(eq_table) {
            var row_elems = collapseByRow($(this));
            // var col_elems = collapseByColumn($(this));


            // if(row_elems["elem_to_collapse"] != null){
            //     row_elems["elem_to_collapse"].each(function(){
            //         $(this).parents("tr").eq(0).attr("rVisibilityHeightTD",$(this).parents("tr").eq(0).outerHeight());
            //     })
            //     row_elems["elem_to_collapse"].animate({
            //         height:0
            //     },function(){
            //         if(row_elems["elem_to_expand"] != null){
            //             row_elems["elem_to_expand"].animate({
            //                 height:62   
            //             })
            //         }
            //     })
            // }
            // if(row_elems["elem_to_expand"] != null){
            //     row_elems["elem_to_expand"].animate({
            //         height:62   
            //     })
            // }
        })
    }



    var initializePage = {
        "init": function() {
            var self = this;
            //sequence here
            self.disableAllFields();

            var collect_ajax = [];

            collect_ajax.push(this.getFormJson($("#FormID").val()));
            collect_ajax.push(this.getRequestDetails());

            collect_ajax.push(this.getServerTime());





            this.pageLoader(collect_ajax, function() {
                self.displayFixes();



                self.loadImage();



                self.evtSubmitRequest();

                self.addRefreshEvent();

                self.visibilityOnChange();

                self.setFieldsVisibility();

                self.setDefaultValues();

                self.populateFormula();


                self.setData();

                embeded_view.init();

                self.addCommentRequest();

                self.printForm(); // Print Form

                self.removeFiles(); // download attachment

                picklist.init();

                self.commitChangesDefaultVal();
            });
            this.addViewer();
            this.getUserViewer();
            this.seeAllUsers_AddViewers();

        },
        "loadImage": function() {
            // var selection = $(".form_upload_photos").find("img.getFields");

            // selection.each(function() {
            //     var value_img = $(this).attr("src");
            //     if (value_img != "/images/avatar/large.png") {
            //         $(this).attr("src", "/" + value_img);
            //     }

            // });
        },
        "pageLoader": function(passArrayOfAjax, PL_Callback) {
            if (typeof PL_Callback != "undefined") {
                //catch undefined
            }
            var self = this;
            var args_ajax = arguments;//infinite argument
            var css_design =
                    'body .fl-user-header-wrapper{' +
                    'z-index:100;' +
                    'position:relative;' +
                    '}' +
                    'body .form-name-title{' +
                    // 'z-index:100;'+
                    'position:relative;' +
                    // 'top:60px;'+
                    // 'top:0px;'+
                    // 'margin-top: 24px;'+
                    'left:0;' +
                    '}' +
                    'body .display_form_status{' +
                    'position: relative;' +
                    // 'top: 100px;'+
                    'top: 0px;' +
                    // 'z-index: 100;' +
                    'left:0;' +
                    'width:100%;' +
                    '}' +
                    'body .bgs-header{' +
                    'position: fixed;' +
                    // 'top: 0px;'+
                    // 'top: -105px;'+
                    'top: -50px;' +
                    'z-index: 99;' +
                    'left:0;' +
                    'width: 100%;' +
                    // 'height: 174px;'+
                    // 'height: 120px;' +
                    'height: auto;' +
                    'background-color: rgba(255,255,255,0.9);' +
                    'box-shadow: 0px 0px 5px #222;' +
                    '}' +
                    '.fl-content{' +
                    '}' +
                    'body .form-action-navs{' +
                    'position: relative;' +
                    // 'top: 140px;'+
                    'top: 0px;' +
                    'z-index: 100;' +
                    'margin:0px' +
                    // 'left:0;' +
                    '}';

            $(".append-script-design").html(css_design);

            if ($(".page-loader-overlay").length >= 1) {
                return $(".page-loader-overlay");
            } else {
                var page_loader =
                        $('<div class="page-loader-overlay">' +
                                '<div class="align-middle">' +
                                '<div class="loader-bar-container align-center">' +
                                '<div class="spinner display load_m">' +
                                '<div class="bar1"></div>' +
                                '<div class="bar2"></div>' +
                                '<div class="bar3"></div>' +
                                '<div class="bar4"></div>' +
                                '<div class="bar5"></div>' +
                                '<div class="bar6"></div>' +
                                '<div class="bar7"></div>' +
                                '<div class="bar8"></div>' +
                                '<div class="bar9"></div>' +
                                '<div class="bar10"></div>' +
                                '</div>' +
                                '</div>' +
                                '</div>' +
                                '</div>');

                $("html").prepend(page_loader);
                var ajaxArray = (typeof passArrayOfAjax === "undefined") ? [] : passArrayOfAjax;

                var loader_bar_container = $(".page-loader-overlay").find(".loader-bar-container");

                //SET DEFAULT AJAX HERE
                //SAMPLE: ajaxArray.push(self.getServerTime()); 
                //EVERY TIME this.pageLoader calls, the set ajax here executes

                loading_progress_added = 100 / ajaxArray.length;

                //SET WHEN TO FADEOUT THE PAGE LOADING
                var vi = setVariableInterval(function() {
                    var loader_bar_container = $(".page-loader-overlay").find(".loader-bar-container");
                    var parent_outerW = loader_bar_container.outerWidth();
                    //EXECUTE ALL AJAX HERE $.when
                    // console.log("ETO NA ANG WHENN",ajaxArray);
                    $.when.apply("args_variable_name", ajaxArray).done(function() {
                        //DO SOMETHING WHEN ALL AJAX IS DONE
                        if (typeof PL_Callback != "undefined") {
                            this.page_loader = page_loader;
                            PL_Callback.call(this);
                        }
                        //LOADING OVERLAY FADEOUT
                        // var loading_containerW = loader_bar_container.outerWidth();
                        // loader_bar_container.find(".label").text("Loading 100%");
                        // loader_bar_container.find(".loader-filler").stop(false, false).animate({
                        //     "width": (parent_outerW)
                        // }, function() {
                        //     page_loader.fadeOut(function() {
                        //         $(this).remove();
                        //     });
                        // })


                        loader_bar_container.closest('.page-loader-overlay').fadeOut(function() {
                            $(this).remove();
                        });
                    });
                    $("html").unbind("DOMSubtreeModified");
                    this.stop();
                }, 1000);

                var counter_modif = 0;
                $("html").bind("DOMSubtreeModified", function() {
                    if (counter_modif == 0) {
                        vi.start();
                    } else {
                        vi.interval = 100; //ADD TIME WHEN THE DOM's ARE BEING MODIFIED BY JAVASCRIPT?
                    }
                    counter_modif++;
                    console.log("LOADING HTML CONTENTS MODIFICATIONS COUNTED: ", counter_modif);
                });
                return page_loader;
            }

        },
        "displayFixes": function() {
            var self = this;
            var form_content = $(".fl-body-content-wrapper");


            //fixing header contents and actions
            var fixes_location = $("body .bgs-header")

            $("body .fl-user-header-wrapper").css("position", "relative").appendTo(fixes_location);
            // $("body .form-name-title").css("position","relative").appendTo(fixes_location);
            $("body .form-action-navs").css("position", "relative").appendTo(fixes_location);
            $("body .display_form_status").css("position", "relative").appendTo(fixes_location);

            //removing unnecessary ui for request client side
            //ui fixes for dynamic table
            if ($(".form-table[border-visible='No']").length >= 1) {
                var ele_style_table = $(
                        "<style>" +
                        ".form-table[border-visible='No'] td{" +
                        "border: none;" +
                        "}" +
                        "</stlyle>"
                        );
                $("body").prepend(ele_style_table);
            }

            if ($(".setObject-drag-handle").length >= 1) {
                $(".setObject-drag-handle").remove();
            }
            if ($(".setObjects_actions").length >= 1) {
                $(".setObjects_actions").remove();
            }
            if ($(".form-builder-ruler").length >= 1) {
                $(".form-builder-ruler").remove();
            }
            if ($(".ui-resizable").length >= 1) {
                $(".ui-resizable").removeClass("ui-resizable");
            }
            if ($(".ui-droppable").length >= 1) {
                $(".ui-droppable").removeClass("ui-droppable");
            }
            if ($(".ui-draggable").length >= 1) {
                $(".ui-draggable").removeClass("ui-draggable");
            }
            if ($(".ui-resizable-handle").length >= 1) {
                $(".ui-resizable-handle").remove();
            }
            if ($(".component-ancillary-focus").length >= 1) {
                $(".component-ancillary-focus").removeClass("component-ancillary-focus");
            }
            if ($(".component-primary-focus").length >= 1) {
                $(".component-primary-focus").removeClass("component-primary-focus");
            }
            if ($(".form-tabbable-pane").length >= 1) {
                $(".form-tabbable-pane").each(function() {
                    $(this).children('.ui-tabs-nav[role="tablist"]').find(".ui-icon-close").hide();
                });
            }
            if ($(".icon-list-alt").length >= 1) {
                $(".icon-list-alt").attr("class", $(".icon-list-alt").attr("class").replace("icon-list-alt", "fa fa-list-alt"));
            }
            //FIX DISPLAY VALUES

            if($('.getFields[data-type="double"]').length >= 1 ){
                $('.getFields[data-type="double"]').change(function(){
                    var unclean_val = $(this).val();
                    var dis_val = unclean_val.replace( (new RegExp(",","g")) ,"");
                    var dis_val_get_str_integer = (dis_val.split("."))[0];
                    var dis_val_parse_number = Number(dis_val);
                    var dis_val_to_percision = dis_val_parse_number.toPrecision(15);
                    if(unclean_val != ""){
                        if(!isNaN(dis_val_parse_number)){
                            if(dis_val_get_str_integer.length >=1 && dis_val_get_str_integer.length <= 15){
                                $(this).val(Number(dis_val_to_percision));
                            }else if(dis_val.length == 0){
                                $(this).val(0);
                            }else if(dis_val_get_str_integer.length >= 16){
                                {//version 1
                                    // NotifyMe($(this), "The value is too big exponential");
                                    // $(this).val(dis_val_to_percision);
                                }
                                
                                {//version 2
                                    validationNotification($(this), "The value is too big your value will be rounded off to 15 digit");
                                    var rounded = Math.round(dis_val.replace(".","").insertReplaceAt(15,0,"."));
                                    $(this).val(rounded);
                                }
                            }
                        }else{
                            validationNotification($(this), "The value you entered is not a number");
                            // $(this).val(0);
                        }
                    }
                });
            }

            if ($('input[data-type="dateTime"]').length >= 1) {

                var disabledDays = [];
                $('input[data-type="dateTime"]').datetimepicker({
                    changeMonth: true,
                    dateFormat: 'yy-mm-dd',
                    beforeShowDay: function(date) {
                        //console.log(this);
                        var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
                        for (i = 0; i < disabledDays.length; i++) {
                            if ($.inArray((m + 1) + '-' + d + '-' + y, disabledDays) != -1) {
                                return [false, 'red', 'This is Holiday'];
                            }
                        }
                        return [true];
                    }
                });
                if ($('input[data-type="dateTime"]').val().length >= 1) {
                    // replace value of date pickers

                    $('input[data-type="dateTime"]').each(function() {

                        $(this).val(ThisDate($(this).val()).formatDate("Y-m-d H:i"));
                    });
                }
                $('input[data-type="dateTime"]').each(function(eqi) {
                    if ($(this).attr("readonly")) {
                        //$(this).datetimepicker("option", "disabled", true);
						$(this).datetimepicker("destroy");
                    }
                });
            }
            if ($('input[data-type="date"]').length >= 1) {
                $('input[data-type="date"]').datepicker({
                    'dateFormat': 'yy-mm-dd',
                    "beforeShow": function() {
                        // setTimeout(function(){
                        $('.ui-datepicker').css('z-index', 100);
                        // }, 0);
                    },
                    changeMonth: true
                });
                if ($('input[data-type="date"]').val().length >= 1) {
                    // replace value of date pickers
                    $('input[data-type="date"]').each(function() {
                        if (ThisDate($(this).val()) == "Invalid Date") {
                            // $(this).val("");
                        } else {
                            $(this).val(ThisDate($(this).val()).formatDate("Y-m-d"));
                        }

                    });
                }
                $('input[data-type="date"]').each(function() {
                    if ($(this).attr("readonly")) {
                        //$(this).datepicker("option", "disabled", true);
						$(this).datepicker("destroy");
                    }
                })
            }
            if ($('input[data-type="time"]').length >= 1) {
                $('input[data-type="time"]').datetimepicker({
                    changeMonth: true,
                    dateFormat: '',
                    timeFormat: 'HH:mm',
                    timeOnly: true
                });
                //if ($('input[data-type="time"]').val().length >= 1) {
                //    //replace value of date pickers
                //    $('input[data-type="time"]').each(function() {
                //        if (ThisDate($(this).val()) == "Invalid") {

                //        }
                //        $(this).val(ThisDate($(this).val()).formatDate("Y-m-d"));
                //    });
                //}
                $('input[data-type="time"]').each(function() {
                    if ($(this).attr("readonly")) {
                        //$(this).datetimepicker("option", "disabled", true);
						$(this).datetimepicker("destroy");
                    }
                })
            }
            if ($('textarea.form-textarea.getFields[data-type="longtext"]').length >= 1) {
                $('textarea.form-textarea.getFields[data-type="longtext"]').css({
                    "resize": "none"
                });
            }
            if ($(".form-tabbable-pane").length >= 1) {
                $(".edit-title-tab-panel").remove();
                $(".li-add-new-tab-panel").remove();
                $(".scroll-achor-ul-tab-nav").css('color','gray');

                if($(".form-tabbable-pane").find(".ul-scroll-anchor").length >= 1){
                    $(".form-tabbable-pane").each(function(){
                        $(this).find(".ul-scroll-anchor").eq(0).remove();
                    });
                }
                $(".form-tabbable-pane").each(function(eqi_ftp) {
                    $(this).find(".ui-state-active").removeClass("ui-state-active");
                    $(this).tabPanel({
                        tabNavSortable:false
                        //resizableContent:true,
                        //resizableContentContainment:".preview_content"
                    });
                });
                $(".edit-title-tab-panel").remove();
                $(".li-add-new-tab-panel").remove();
                $(".scroll-achor-ul-tab-nav").css('color','gray');
                //has-scroll="true"
                //ui-tabs-nav-scrollable="true"

                // $(".scroll-achor-ul-tab-nav").on({
                //     "mouseenter":function(){
                //         $(this).stop(false,false).animate({
                //             "opacity":1
                //         });
                //     },
                //     "mouseleave":function(){
                //         $(this).stop(false,false).animate({
                //             "opacity":0
                //         });
                //     }
                // })
                // $('.ui-tabs-nav, .scroll-achor-ul-tab-nav').on({
                //     "mouseenter":function(){
                //         if($(this).hasClass('ui-tabs-nav')){
                //             $(this).parent().find('.ul-scroll-anchor:eq(0) .scroll-achor-ul-tab-nav').stop(false,false).animate({
                //                 "opacity":1
                //             });
                //         }else{
                //             $(this).stop(false,false).animate({
                //                 "opacity":1
                //             });
                //         }
                //     },
                //     "mouseleave":function(){
                //         if($(this).hasClass('ui-tabs-nav')){
                //             $(this).parent().find('.ul-scroll-anchor:eq(0) .scroll-achor-ul-tab-nav').stop(false,false).animate({
                //                 "opacity":0
                //             });
                //         }else{
                //             $(this).stop(false,false).animate({
                //                 "opacity":0
                //             });
                //         }
                //     }
                // })
            }

            if ($(".form-table").length >= 1) {
                $(".form-table").each(function() {
                    if ($(this).closest(".table-wrapper").length >= 1) {
                        $(this).closest(".table-wrapper").find(".table-actions-ra").remove();
                        if ($(this).closest(".table-wrapper").find(".ui-resizable-handle").length >= 1) {
                            $(this).closest(".table-wrapper").find(".ui-resizable-handle").remove();
                        }
                    } else if ($(this).find(".table-actions-ra").length >= 1) {
                        $(this).find(".table-actions-ra").remove();
                        if ($(this).find(".ui-resizable-handle").length >= 1) {
                            $(this).find(".ui-resizable-handle").remove();
                        }
                    }

                    if ($(this).attr("repeater-table")) {
                        if ($(this).attr("repeater-table") == "true") {
                            // $(this).closest(".")//DITO NA AKO
                            self.makeRepeaterTable($(this), function(table_ui) {
                                $(table_ui).children("tbody").children("tr").on({
                                    "mouseenter": function(e) {
                                        $(this).children("td").children(".td-relative").children(".repeater-action").not(".disable-repeater-action").stop(false, false).animate({
                                            "opacity": 1
                                        }, 500);
                                    },
                                    "mouseleave": function(e) {
                                        $(this).children("td").children(".td-relative").children(".repeater-action").not(".disable-repeater-action").stop(false, false).animate({
                                            "opacity": 0
                                        }, 500);
                                    }
                                });
                                $(table_ui).children("tbody").children("tr").find(".disable-repeater-action").css("display", "none");
                            });
                            var object_field_ele = $(this).closest(".setOBJ").find("#obj_fields_" + $(this).closest(".setOBJ").attr("data-object-id"));
                            // object_field_ele.css({
                            //   "width":(object_field_ele.outerWidth())+"px",
                            //   "height":(object_field_ele.outerHeight())+"px",
                            //   "overflow":"auto"
                            // });
                            // object_field_ele.children(".table-wrapper").css({
                            //   "margin-left":"40px"
                            // })
                            object_field_ele.css({
                                "overflow": "auto"
                            });
                        }
                    }

                    $(this).closest(".setOBJ").css({"height": ($(this).closest(".setOBJ").height()) + "px"});
                    if ($(this).closest(".setOBJ").css("display") == "none") {
                    } else {
                        $(this).closest(".setOBJ").css({"display": "block"});
                    }
                });
            }
            if ($(".getFields[data-input-type='Currency']").length >= 1) {
                $(".getFields[data-input-type='Currency']").each(function() {
                    $(this).on("change.currency_format", function() {
                        if ($.isNumeric($(this).val())) {
                            var value_number = parseFloat($(this).val());
                            $(this).val(value_number.currencyFormat());
                        } else {
                            var value_nito = $(this).val()
                            var sanitized_val = value_nito.replace(/[\s,]/g, "");
                            if ($.isNumeric(sanitized_val)) {
                                var value_number = parseFloat(sanitized_val);
                                $(this).val(value_number.currencyFormat());
                            }
                        }
                    });
                });
                $(".getFields[data-input-type='Currency']").change();
            }
            // NOTE STYLE FIELD FUNCTIONALITY
            if ($('.content-editable-field[contenteditable="true"]').length >= 1) {

                var ele_style_cef = $(
                        "<style>" +
                        ".content-editable-field[contentEditable=true]:empty:not(:focus):before {" +
                        "content:attr(placeholder)" +
                        "color:rgb(150, 150, 150)" +
                        "}" +
                        ".content-editable-field[contentEditable=true]:empty:before {" +
                        "content:attr(placeholder)" +
                        "color:rgb(200,200,200)" +
                        "}" +
                        "</stlyle>"
                        );
                $("body").prepend(ele_style_cef);

                $("body").on('keypress.notesChange keydown.notesChange keyup.notesChange', '.content-editable-field[contenteditable="true"]', function(e) {
                    var disVal = "";
                    if (e.type == "keypress" || e.type == "keydown") {
                        var ele_dis = $(this);
                        var selection_index = /*getCaretPosition(ele_dis[0])*/ $(ele_dis).caret();//startPoint endPoint
                        // console.log(selection_index)
                    }
                    if (e.type == "keypress") {
                        // console.log("keypress", e)
                        // var keyCode = (typeof e.which == "number")?e.which:((e.keycode)?e.keycode:e.keyCode);
                        var charCode = e.charCode;
                        disVal = "" + String.fromCharCode(charCode);
                        var self_ele = $(this);
                        var oid = $(this).parents(".setOBJ").eq(0).attr("data-object-id");
                        var dis_val = getContentEditableVal(self_ele);
                        // console.log("BRAWL",selection_index["start"], selection_index["end"]-selection_index["start"])
                        dis_val = dis_val.insertReplaceAt(selection_index["start"], (selection_index["end"]) - (selection_index["start"]), disVal);
                        // console.log("VALUEPRESSED", dis_val)
                        var getField = self_ele.parents(".note-style-wrap-contents").eq(0).find(".getFields_" + oid);

                        getField.val(dis_val);
                        getField.trigger("change",[{
                            "notes_change_not_allow":true
                        }]);
                    }else if(e.type == "keydown"){
                        // console.log("SELECTION",selection_index["endPoint"],selection_index["startPoint"])
                        // var keyCode = (typeof e.which == "number")?e.which:((e.keycode)?e.keycode:e.keyCode);
                        // var self_ele = $(this);
                        // var oid = $(this).parents(".setOBJ").eq(0).attr("data-object-id");
                        // var dis_val = getContentEditableVal(self_ele);
                        // var getField = self_ele.parents(".note-style-wrap-contents").eq(0).find(".getFields_"+oid);
                        // if(keyCode == 8){

                        //     if( (selection_index["endPoint"]-selection_index["startPoint"]) == 0){
                        //         // console.log(selection_index["endPoint"],selection_index["startPoint"],"BOOOM",selection_index["startPoint"]-1);
                        //         // dis_val = dis_val.insertReplaceAt(selection_index["startPoint"]-1, 1, "");
                        //     }else{
                        //         // console.log(selection_index["endPoint"],selection_index["startPoint"],"BOOOM",selection_index["startPoint"]-1);
                        //         // dis_val = dis_val.insertReplaceAt(selection_index["startPoint"], selection_index["endPoint"]-selection_index["startPoint"], "");
                        //     }
                        // }
                        // if(keyCode == 13){
                        //     dis_val = dis_val.insertReplaceAt(selection_index["startPoint"], selection_index["endPoint"]-selection_index["startPoint"], "\n");
                        // }
                        // getField.val(dis_val);
                        var self_ele = $(this);
                        var oid = $(this).parents(".setOBJ").eq(0).attr("data-object-id");
                        var getField = self_ele.parents(".note-style-wrap-contents").eq(0).find(".getFields_"+oid);
                        getField.trigger("change",[{
                            "notes_change_not_allow":true
                        }]);
                    }else if(e.type == "keyup"){
                        // console.log("UPPP")
                        var self_ele = $(this);
                        var oid = $(this).parents(".setOBJ").eq(0).attr("data-object-id");
                        var dis_val = getContentEditableVal(self_ele);
                        var getField = self_ele.parents(".note-style-wrap-contents").eq(0).find(".getFields_" + oid);
                        getField.val(dis_val);
                        getField.trigger("change",[{
                            "notes_change_not_allow":true
                        }]);
                    }
                });
                $("body").on('change.notesChange','.noteStyleField.getFields',function(e,data_event){
                    // console.log("NOTESCHANGE ALLOWS",data_event)
                    if(data_event){
                        if(data_event["notes_change_not_allow"]){
                            return false;
                        }else{
                            
                        }
                    }else{
                        
                    }
                    var self = $(this);
                    var display_location = self.parents(".note-style-wrap-contents").eq(0).find(".content-editable-field[contenteditable]").eq(0);
                    var regEks = new RegExp(".*(?=\n|$)", "g"); // change to
                    var val_matches = self.val().match(regEks).filter(Boolean);
                    // console.log("TESTMATCHES::", val_matches)
                    var collect_val = [];
                    for (var ii in val_matches) {
                        collect_val.push("<div>" + val_matches[ii] + "</div>");
                    }
                    display_location.html(collect_val.join(""));
                });
                $("[fluid-container-cell]").each(function(){
                    var dis_ele = $(this);
                    var dis_ele_top = Number(dis_ele.css('top').replace("px",""));
                    var dis_ele_left = Number(dis_ele.css('left').replace("px",""));
                    var dis_ele_setOBJ = dis_ele.parents(".setOBJ").eq(0);
                    var dis_doi = dis_ele_setOBJ.attr("data-object-id");

                    if(dis_ele_setOBJ.parent().hasClass("td-relative")){
                        dis_ele_setOBJ.css("position","relative");
                    }
                    if(dis_ele_top >= 1){
                        dis_ele.css({
                            "top":"0px",
                            "margin-top":(dis_ele_top)+"px"
                        });

                    }
                    if(dis_ele_left >= 1){
                        dis_ele.css({
                            "left":"0px",
                            "margin-left":(dis_ele_left)+"px"
                        });
                    }
                });
                $(".noteStyleField.getFields").trigger("change");
                $('.setOBJ[data-type="noteStyleTextarea"]').each(function(eq_i_ns){
                    var dis_ele = $(this);
                    var doi = dis_ele.attr("data-object-id");
                    var dis_getfield = dis_ele.find(".getFields_"+doi);
                    if(dis_getfield.attr("disabled")){
                        dis_ele.find(".content-editable-field_"+doi).attr("contenteditable",false);

                    }
                    dis_ele.find(".content-editable-field_"+doi).css({
                        "width":"",
                        "height":""
                    });
                });
            }
        },
        "evtSubmitRequest": function() {
            var self = this;
            $('body').on('click', '#fl-action-option .fl-action-submit', function() {
                var selected_action_name = this.getAttribute( "value" )
                console.log(selected_action_name)
                // alert(selected_action_name)
                var pathname = window.location;
                if (getParametersName("view_type", pathname) == "preview") {
                    return false;
                }
                self.getKeywordFields();




                var server_date = (typeof $("body").data().getServerTimeData === "undefined") ? null : $("body").data().getServerTimeData;
                if (server_date == null) {
                    console.log("SERVER DATE DID NOT GET", server_date)
                } else {
                    console.log("SERVER DATE GET", server_date)
                }

                var invalid_datas = 0;
                //set data validation
                $(".setOBJ").each(function() {
                    
                    var data_obj_id = $(this).attr("data-object-id");
                    var the_field = $(this).find(".getFields_" + data_obj_id);
                    //console.log("TESTING ATTR SELECTOR JQUERY",the_field);
                    if (
                            (typeof the_field.attr("required") != "undefined" && the_field.val() != "") ||
                            (typeof the_field.attr("required") == "undefined")
                    ) {
                        
                        var invalid_field_data = 0;
                        console.log("BDT",the_field)
                        if (the_field.attr("field-formula-validation")) {
                            console.log("TEST VALIDTIOn",the_field.attr("field-formula-validation"))
                            if (the_field.attr("field-formula-validation") != null || the_field.attr("field-formula-validation") != '') {
                                var field_data_validation_message = "Invalid value";
                                if (typeof the_field.attr("field-formula-validation-message") != "undefined") {
                                    field_data_validation_message = "" + the_field.attr("field-formula-validation-message");
                                }

                                var field_data_validation_formula = the_field.attr("field-formula-validation");
                                if (field_data_validation_formula.indexOf("@Date_Only(") >= 0) {
                                    field_data_validation_formula = field_data_validation_formula.replace(/@Date_Only\(/g, "Date_Only(");
                                }
                                var FDVF_splitted;
                                var getting_name_re = new RegExp("@[a-zA-Z][a-zA-Z0-9_]*","g");
                                try {
                                    //FDVF_splitted = field_data_validation_formula.split(/<=|>=|==|!=|<|>|Date_Only\(|\(|\)|!/g);
                                    
                                    FDVF_splitted = field_data_validation_formula.match(getting_name_re);
                                    if (typeof FDVF_splitted === "object"){
                                        FDVF_splitted = FDVF_splitted.filter(Boolean);
                                    }
                                    
                                    if (FDVF_splitted.length >= 1) {
                                        for (var u_i = 0; u_i < FDVF_splitted.length; u_i++) {
                                            FDVF_splitted[u_i] = $.trim(FDVF_splitted[u_i]);
                                        }
                                    }
                                } catch (error) {
                                    //
                                }
                                console.log("OHH NOOOO!!")
                                console.log(FDVF_splitted)
                                //check if date or number or other
                                try {
                                    var numeric_data_type = 0;
                                    var date_data_type = 0;
                                    var other_data_type = 0;
                                    var data_type_status = "";
                                    for (var ctr = 0; ctr < FDVF_splitted.length; ctr++) {
                                        if (typeof FDVF_splitted[ctr] == "undefined" || $.trim(FDVF_splitted[ctr]) == "") {
                                            continue;
                                        }
                                        string_field_name = $.trim(FDVF_splitted[ctr]).split("@").join("");
                                        field_affected_on_formula = $('[name="' + string_field_name + '"]');
                                        if (field_affected_on_formula.length >= 1) {
                                            var FAOF_val = field_affected_on_formula.val();
                                            if (typeof field_affected_on_formula.attr("data-input-type") != "undefined") {
                                                if (field_affected_on_formula.attr("data-input-type") == "Currency") {
                                                    FAOF_val = FAOF_val.replace(/,/g, "");
                                                }
                                            }
                                            if ($.isNumeric(FAOF_val)) {
                                                numeric_data_type++;
                                            } else if (!isNaN(Date.parse(FAOF_val))) {
                                                date_data_type++;
                                            } else if (FAOF_val == "") {
                                                other_data_type++;
                                                //return true; //hindi na i rereturn kasi meron pala sa formula kapag ung value ng field walang laman ok lang
                                                // I return so that the required field validation of jewel will not be affected
                                            } else {
                                                // alert("NAKO: "+string_field_name);
                                                // alert(FAOF_val);
                                                other_data_type++;
                                            }
                                        } else {
                                            // console.log("dito ung mga value na hindi fieldname")
                                            // console.log(string_field_name)
                                            if (("@" + string_field_name) == "@Now") {
                                                date_data_type++;
                                            } else if (("@" + string_field_name) == "@Today") {
                                                date_data_type++;
                                            } else {
                                                if ($.isNumeric(string_field_name)) {
                                                    numeric_data_type++;
                                                } else if (!isNaN(Date.parse(string_field_name))) {
                                                    date_data_type++;
                                                } else {
                                                    // alert("eto:::"+string_field_name)
                                                    // alert("NAKO: "+string_field_name);
                                                    // alert($('[name="'+string_field_name+'"]').length);
                                                    other_data_type++;
                                                }
                                            }
                                        }
                                    }
                                    var data_consitency_status = 0;
                                    if (numeric_data_type >= 1) {
                                        data_type_status = "numeric";
                                        data_consitency_status++;
                                    }
                                    if (date_data_type >= 1) {
                                        data_type_status = "date";
                                        data_consitency_status++;
                                    }
                                    if (other_data_type >= 1) {
                                        data_type_status = "unknown";
                                        //data_consitency_status++;
                                        // console.log("ETOHAN unknown");
                                        // console.log(the_field)
                                        //requiredFields_v2(the_field);
                                        // alert(" value: "+the_field.val())
                                        //validationNotification(the_field, "Invalid value");
                                        //alert(44)
                                        //invalid_field_data++;
                                    }
                                    // console.log(
                                    //     "numeric:"+numeric_data_type+
                                    //     "\ndate:"+date_data_type+
                                    //     "\nother:"+other_data_type
                                    // )
                                } catch (err) {

                                }
                                // alert("OK PA ETO TINGIN\n"+field_data_validation_formula)
                                if (invalid_field_data >= 1) {
                                    //requiredFields_v2(the_field);
                                    // console.log("invalid field data other");
                                    // console.log(the_field)

                                    // alert("invalid field data")
                                    // alert(field_data_validation_formula)
									console.log("invalid_field_data")
                                    validationNotification(the_field, "Invalid value");
                                    //alert(33)
                                    invalid_datas++;
                                    return true;
                                //} else if (data_consitency_status != 1) {
                                    //requiredFields_v2(the_field);
                                    // console.log("data consistent");
                                    // console.log(the_field)
									// console.log("data_consitency_status")
                                    //validationNotification(the_field, "Invalid value");
                                    //alert(22)
                                    //invalid_datas++;
                                    //return true;
                                } else {
                                    console.log("wALA EERORe")
                                    try {
                                        console.log("field_data_validation_formula")
                                        console.log(FDVF_splitted)
                                        // alert("OK")

                                        for (var ctr = 0; ctr < FDVF_splitted.length; ctr++) {
                                            if (typeof FDVF_splitted[ctr] == "undefined" || $.trim(FDVF_splitted[ctr]) == "") {
                                                continue;
                                            }
                                            string_field_name = $.trim(FDVF_splitted[ctr]).split("@").join("");
                                            field_affected_on_formula = $('[name="' + string_field_name + '"]');
                                            console.log("ituu")
                                            console.log(field_affected_on_formula)
                                            if (field_affected_on_formula.length >= 1) {
                                                var FAOF_val = field_affected_on_formula.val();
                                                if (typeof field_affected_on_formula.attr("data-input-type") != "undefined") {
                                                    if (field_affected_on_formula.attr("data-input-type") == "Currency") {
                                                        FAOF_val = FAOF_val.replace(/,/g, "");
                                                    }
                                                }
                                                if (data_type_status == "numeric") {
                                                    field_data_validation_formula = field_data_validation_formula.replace("@" + string_field_name, FAOF_val);
                                                } else if (data_type_status == "date") {
                                                    // console.log("@fieldName "+string_field_name+":"+FAOF_val); //DITO NA AKO
                                                    field_data_validation_formula = field_data_validation_formula.replace("@" + string_field_name, Date.parse(FAOF_val));
                                                } else if ($.isNumeric(FAOF_val)) {
                                                    field_data_validation_formula = field_data_validation_formula.replace("@" + string_field_name, FAOF_val);
                                                } else {
                                                    field_data_validation_formula = field_data_validation_formula.replace("@" + string_field_name, "\"" + FAOF_val + "\"");
                                                }
                                            } else {
                                                if (data_type_status == "numeric") {

                                                } else if (data_type_status == "date") {
                                                    if (("@" + string_field_name) == "@Now") {
                                                        // console.log("@Now server_date: "+server_date);
                                                        field_data_validation_formula = field_data_validation_formula.replace("@" + string_field_name, Date.parse(server_date));
                                                    } else if (("@" + string_field_name) == "@Today") {
                                                        //alert(server_date);
                                                        // console.log("server_date: "+server_date)
                                                        var date_from_server = new Date(server_date);
                                                        var today_formatted_from_server = date_from_server.getFullYear() + "-" + (date_from_server.getMonth() + 1) + "-" + date_from_server.getDate();
                                                        // console.log("@Today today_formatted_from_server: "+today_formatted_from_server);
                                                        field_data_validation_formula = field_data_validation_formula.replace("@" + string_field_name, Date.parse(today_formatted_from_server));
                                                    } else {
                                                        // console.log("'yy-mm-dd' string_date: "+string_field_name);
                                                        field_data_validation_formula = field_data_validation_formula.replace(string_field_name, Date.parse(string_field_name));
                                                    }
                                                }
                                            }
                                            // alert("11 "+FDVF_splitted[ctr])
                                            // alert("ETO TINGIN\n"+field_data_validation_formula+" "+ctr)
                                            // console.log(field_affected_on_formula)
                                            // console.log(field_data_validation_formula)
                                        }

                                        // alert(field_data_validation_formula)
                                        console.log("TESTING STRINGS");

                                        console.log(field_data_validation_formula)
                                        field_data_validation_formula = field_data_validation_formula.replace(/@/g,"");
                                        // console.log(eval(field_data_validation_formula))
                                        // console.log(typeof eval(field_data_validation_formula))
                                        //$(".getFname").html(field_data_validation_formula)
                                        if (typeof eval(field_data_validation_formula) == "boolean") {
                                            console.log("pasok")
                                            console.log(eval(field_data_validation_formula))
                                            if (eval(field_data_validation_formula) == true) {
                                                //ok
                                                // alert(field_data_validation_formula)
                                            } else if (eval(field_data_validation_formula) == false) {
                                                // alert(field_data_validation_formula + "ETO?")
                                                // console.log("nag false");
                                                // console.log(field_data_validation_formula);
                                                //hindi ok
                                                //the_field.attr("data-original-title","Invalid value");
                                                //requiredFields_v2(the_field);
                                                // console.log("LAST");
                                                // console.log(the_field);
                                                validationNotification(the_field, field_data_validation_message);
                                                //alert(55);
                                                invalid_datas++;
                                            }
                                        } else {
                                            console.log("pasok32")
                                            validationNotification(the_field, "Invalid result on formula");
                                            invalid_datas++;
                                        }
                                    } catch (err) {
                                        console.log("error")
										//console.log(field_data_validation_formula,eval(field_data_validation_formula))
                                        console.log(field_data_validation_formula)
                                        invalid_datas++;
                                        //invalid_datas
                                    }
                                }
                            }
                        }
                        if (the_field.attr("data-type")) {

                            if (the_field.attr("data-type") == "longtext") {

                            } else if (the_field.attr("data-type") == "float" || the_field.attr("data-type") == "double") {

                                var field_Value = the_field.val();
                                var fieldDataType = the_field.attr('data-input-type');

                                if (fieldDataType == 'Currency') {
                                    field_Value = Number(field_Value.replace(/[^0-9\.]+/g, ""));
                                }

                                if (!$.isNumeric(field_Value) && field_Value != "") {
                                    //requiredFields_v2(the_field);
                                    validationNotification(the_field, "Numbers only");
                                    invalid_datas++;
                                }
                            }
                        }
                    }
                });
                if (invalid_datas >= 1) {
                    showNotification({
                        message: "Please correct the field values",
                        type: "error",
                        autoClose: true,
                        duration: 3
                    });
                } else {
                    var selectedAction = $(this).attr('value');// $('#actionRequestButton option:selected').val();
                    var selectedNode = $(this).attr('action');// $('#actionRequestButton option:selected').attr('action');
                    var selectedWorkflowID = $(this).attr('data-workflow-id'); //$('#actionRequestButton option:selected').attr('data-workflow-id');
                    var message = $(this).attr('message');
                    if (!message || message == '') {
                        message = "Are you sure you want to proceed?";
                    }

                    $('#Node_ID').val(selectedNode);
                    $('#Workflow_ID').val(selectedWorkflowID);

                    // if (selectedAction == '0') {
                    //     showNotification({
                    //         message: "Please select action",
                    //         type: "error",
                    //         autoClose: true,
                    //         duration: 3
                    //     });
                    //     return;
                    // }

                    var hasRequiredError = 0;
                    $(".setOBJ .getFields").each(function() {
                        if ($(this).attr("required")) {
                            //design for required field here
                            if ($(this).attr("type") == "checkbox") {

                            } else {
                                if ($(this).val() == "") {
                                    hasRequiredError++;
                                }
                            }

                        }
                    })
                    if (hasRequiredError > 0) {
                        showNotification({
                            message: "Fill out all required fields",
                            type: "error",
                            autoClose: true,
                            duration: 3
                        });
                        return;
                    }
                    ;

                    self.getData();
                    jConfirm(message, '', '', '', '', function(r) {
                        if (r) {
                            self.formatCurrency();



                            // $('#frmrequest').submit();    
                            //var submit_ajax = [];
                            //submit_ajax.push();
                            //$('[data-input-type="Currency"]').each(function(){
                            //    alert($(this).val());
                            //})
                            ui.block();
                            $('#frmrequest').ajaxSubmit({
                                data: {},
                                success: function(data) {
                                    //  Get only the json data
                                    data = data.substring(data.indexOf('{'), data.length);
                                    console.log(data);

                                    var parsedData = JSON.parse(data);

                                    console.log(parsedData);

                                    $.event.trigger({
                                        type: 'documentCreated',
                                        documentData: parsedData
                                    });

                                    $.event.trigger({
                                        type: 'sendNotification',
                                        sendTo: [parsedData.Processor],
                                        notificationData: {
                                            notificationType: 'REQUEST_ACTION',
                                            requestData: parsedData
                                        }
                                    });
                                    
                                    {  //AUTO GRAMMAR MESSAGE ACTION SUBMIT // by michael
                                        var spl_selected_action_name = selected_action_name.split("");
                                        var last_char_sel_action = selected_action_name.split("").pop();
                                        var temp_message = "";
                                        if(last_char_sel_action == "e"){
                                            temp_message = selected_action_name+"d";
                                        }else if(selected_action_name.toLowerCase() == "submit"){
                                            temp_message = selected_action_name+"ted";
                                        }else if(last_char_sel_action == "t"){
                                            temp_message = selected_action_name+"ed";
                                        }else if(last_char_sel_action == "y"){
                                            spl_selected_action_name.pop();
                                            temp_message = spl_selected_action_name.join("")+"ied";
                                        }else{
                                            temp_message = selected_action_name+"ed";
                                        }
                                    }
                                    

                                    showNotification({
                                        message: "Request has been "+temp_message+", Redirecting...",
                                        type: "success",
                                        autoClose: true,
                                        duration: 2
                                    }).css("z-index",100000000);
                                    
                                    setTimeout(function(){
                                        ui.unblock();
                                        window.location = "/user_view" + parsedData.headerLocation;
                                    },2000);
                                    //  redirect to home
                                }
                            })

                            // self.pageLoader(submit_ajax, function() {
                            //     //CALLBACK WHEN AJAX IS FINISHED
                            // });

                        }
                    });
                }

            });
        },
        //AJAX FUNCTIONS
        "getServerTime": function() {
            var ajaxTime = (new Date()).getTime();
            return $.ajax({
                "url": "/ajax/getDateToday",
                "async": true,
                "type": "POST",
                "cache": false,
                "beforeSend": function(xhr) {
                    // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                },
                "data": {"access": "get_date"},
                "dataType": "html"
            }).done(function(data) {
                var responseTime = (new Date()).getTime() - ajaxTime;

                var serverOBJTIME = new Date(data);

                serverOBJTIME = serverOBJTIME.setTime(serverOBJTIME.getTime())

                var temp = $("body").data();

                temp.getServerTimeData = serverOBJTIME;
                $("body").data(temp);

                setInterval(function() {
                    var temp = $("body").data();
                    var localTime = new Date();
                    var serverTime = new Date(temp.getServerTimeData);
                    var updatedServerTime = new Date(serverTime.setHours(serverTime.getHours() + (localTime.getHours() - serverTime.getHours()))); //ADDING HOURS
                    updatedServerTime = new Date(serverTime.setMinutes(serverTime.getMinutes() + (localTime.getMinutes() - serverTime.getMinutes()))); //ADDING MINUTES
                    updatedServerTime = new Date(serverTime.setSeconds(serverTime.getSeconds() + (localTime.getSeconds() - serverTime.getSeconds()))); //ADDING SECONDS
                    temp.getServerTimeData = updatedServerTime;
                    $("body").data(temp);
                }, 1000)





                //ADD PROGRESS FOR PAGE LOADER
                var loader_bar_container = $(".page-loader-overlay").find(".loader-bar-container");
                var loading_container = loader_bar_container.outerWidth();
                var loading_filler = loader_bar_container.find(".loader-filler").outerWidth();
                loader_bar_container.find(".loader-filler").css({
                    "width": (getPercent(loading_container, loading_filler) + loading_progress_added) + "%"
                });
                loading_filler = loader_bar_container.find(".loader-filler").outerWidth();
                loader_bar_container.find(".label").text("Loading " + Math.ceil(getPercent(loading_container, loading_filler)) + "%");

                {
                    // loader_bar_container.find(".loader-filler").stop(false,false).animate({
                    //     "width":(getPX(loading_container , getPercent(loading_container,loading_filler)+loading_progress_added) )
                    // },function(){
                    // 	var loading_container = loader_bar_container.outerWidth();
                    // 	var loading_filler = loader_bar_container.find(".loader-filler").outerWidth();
                    // 	loader_bar_container.find(".label").text("Loading "+Math.ceil( getPercent(loading_container,loading_filler) )+"%");
                    // });
                }



            }).fail(function() {
                console.log("SERVER DATE : ERROR ON GETTING AJAX POST METHOD SERVER TIME.");
            })
        },
        getKeywordFields: function() {
            var keywordFields = [];
            $('.pickListButton').each(function() {
                var inputField = $(this).attr('return-field');
                var inputFieldName = $('#' + inputField).attr('name');
                var inputCode = $('#' + inputField).attr('code');
                keywordFields.push({
                    Field: inputFieldName,
                    Code: inputCode
                });
            });
            console.log(keywordFields);
            $('#KeywordsField').val(JSON.stringify(keywordFields));
        },
        disableAllFields: function() {
            $(".setOBJ .getFields").attr("disabled", "disabled");
            //hide picklist if enabled
            $(".pickListButton").hide();
        },
        getRequestDetails: function() {
            var formId = $('#FormID').val();
            var self = this;
            var requestId = $("#ID").val();
            var currentUser = $("#CurrentUser").val();
            var tmpFieldEnabled = $("#fieldEnabled").val();
            //var tmpFieldHidden = $("#ID").val();
            //var tmpFieldRequired = $("#ID").val();
            var location = window.location.pathname;
            if (requestId != '0' && requestId != '') {
                if (location == '/workspace') {
                    if ($('body').children(".submit-overlay").length == 0) {
                        var submit_overlay = $('<div class="submit-overlay" style="background:url(/images/loader/loader.gif);z-index:1002;background-repeat:no-repeat;background-attachment:fixed;background-color:rgba(200,200,200,0.5);background-position:center;position:fixed;width:100%;height:100%;text-align:center;vertical-align:middle;">Loading...</div>');
                        $('body').prepend(submit_overlay);
                    }
                }
                var pathname = window.location;
                if (getParametersName("view_type", pathname) == "update") {
                    var loc = "/ajax/printdetails";
                } else {
                    var loc = "/ajax/requestdetails";
                }
                return $.ajax({
                    type: 'POST',
                    url: loc,
                    data: {
                        FormID: formId,
                        RequestID: requestId
                    },
                    success: function(result) {
                        try {
                            // var resultJson = JSON.parse(result);
                            var resultJson = result;
                            for (var index in resultJson) {
                                for (var key in resultJson[index]) {
								
                                    if ($('[name="' + key + '[]"]').attr("type") == "checkbox") {
                                        $('[name="' + key + '[]"]').each(function() {
                                            if (resultJson[index][key]) {
                                                var checkbox_value = resultJson[index][key].split(",");
                                                var checkbox_value_new = resultJson[index][key].split("|^|");

                                                if (checkbox_value.indexOf($(this).val()) >= 0 || checkbox_value_new.indexOf($(this).val()) >= 0) {
                                                    $(this).attr("checked", "checked")
                                                }
                                            }
                                        });
                                    } else if ($('[name="' + key + '"]').attr("type") == "radio") {
                                        // $('[name="' + key +'"]').each(function(){
                                        // });
                                        $('[name="' + key + '"][value="' + resultJson[index][key] + '"]').prop("checked", true);
                                    } else {
                                        if (key == "fieldEnabled" || key == "fieldRequired" || key == "fieldHiddenValues") {
                                            $("." + key).text(resultJson[index][key]);
                                            if ($('[name="' + key + '"]').prop("tagName") == "TEXTAREA") {
                                                $('[name="' + key + '"]').text(resultJson[index][key]);
                                                $('[name="' + key + '"]').val(resultJson[index][key]);
                                            } else {
                                                $('[name="' + key + '"]').attr("value", resultJson[index][key]);
                                                $('[name="' + key + '"]').val(resultJson[index][key]);
                                            }
                                        } else if (key == 'TrackNo') {
                                            $('[name="' + key + '"]').val(resultJson[index][key]);
                                            $('#trackno_display').text($('#TrackNo').val());
                                        } else if (key == 'Requestor_Fullname') {
                                            //Requestor_Fullname
                                            // $('[name="' + key + '"]').attr("value", resultJson[index][key]);
                                            // $('#requestor_display').text(resultJson[index][key]);
                                            $('[name="' + key + '"]').attr("value", resultJson[index][key]);
                                            $('#requestor_display').text(resultJson[index][key]);
                                        } else if (key == 'Processor_Name') {
                                            $('[name="' + key + '"]').attr("value", resultJson[index][key]);
                                            $('#processor_display').text(resultJson[index][key]);
                                        } else if (key == 'Status') {
                                            $('[name="' + key + '"]').val(resultJson[index][key]);
                                            $('#status_display').text($('#Status').val());
                                        } else {
                                            if ($('[name="' + key + '"]').prop("tagName") == "TEXTAREA") {
                                                $('[name="' + key + '"]').text(resultJson[index][key]);
                                            } else if ($('[name="' + key + '"]').prop("tagName") == "SELECT") {
                                                $('[name="' + key + '"] option[value="' + resultJson[index][key] + '"]').attr("selected", "selected")
                                            } else {
                                                $('[name="' + key + '"]').attr("value", resultJson[index][key]);
                                                $('[name="' + key + '"]').val(resultJson[index][key]);
                                                //var photos = $('[name="' + key + '"]').parent().next().children().attr("src");

                                                //for submt request with photos
                                                var status = $("#status_display").html();
                                                if (currentUser != resultJson[index][key] && status.indexOf('Updated') >= 0) {
                                                    $('[name="' + key + '"]').parent().parent().parent().parent().attr("data-type", "imageOnly");
                                                } else {
                                                    $('[name="' + key + '"]').parent().parent().parent().parent().attr("data-type", "");
                                                }


                                                if (resultJson[index][key] != null) {
                                                    $(".uploader2").hide();
                                                    //$('[name="' + key + '"]').parent().parent().parent().parent().attr("data-type", "");
                                                    $('[name="' + key + '"]').parent().find('img').attr("src", resultJson[index][key]);
                                                }
                                                if (resultJson[index][key] == "") {
                                                    $('[name="' + key + '"]').parent().find('img').attr("src", "/images/avatar/large.png");
                                                    //$('[name="' + key + '"]').parent().parent().parent().parent().parent().attr("data-type", "");
                                                }
                                                console.log("KEY:"+(key)+"  VALUE:"+(resultJson[index][key]));
                                            }
                                        }

                                    }
                                }
                            }

                            var imported = $("#imported").val();
                            if (imported == "1") {
                                $("[name='fieldEnabled']").val(tmpFieldEnabled);
                                $(".fieldEnabled").html(tmpFieldEnabled);
                                $("#imported").val('');
                            } else {
                                self.getButtons();
                            }
                            if ($('#LastAction').val() == 'null' || $('#LastAction').val() == null || $('#LastAction').val() == '') {
                                $('#lblprocessor_display').hide();
                                $('#processor_display').add($('#processor_display').parents("label").eq(0)).hide();
                            }

                            if ($(".submit-overlay").length >= 1) {
                                $(".submit-overlay").fadeOut(function() {
                                    $(this).remove();
                                });
                            }
                            self.fieldEnabled();
                            self.fieldRequired();
                            self.fieldHiddenValues();
                            //embeded_view.init();

                        } catch (error) {
                            console.log("getRequestDetails ERROR AJAX", error)
                        }
                    },
                    dataType: "json",
                    async: false
                }).fail(function() {
                    console.log("FAIL REQUEST DETAILS");
                })
            } else {
                self.fieldEnabled();
                self.fieldRequired();
                self.fieldHiddenValues();
                computed.init();
                // $(".viewer_action").append('<button class="btn-basicBtn padding_5 cursor tip addViewer" data-original-title="Add Viewer"><i class="icon-user"></i></button>')
                // $(".tip").tooltip();
                //   self.getButtons();
                return "";
            }

        },
        fieldEnabled: function() {
            var fields = ""
            var requestId = $("#ID").val();
            var requestor_id = $("#Requestor").val();
            var currentUser = $("#CurrentUser").val();
            if (requestor_id == currentUser || requestId == 0) {
                fields = $(".fieldEnabled_default").text();
            } else {
                fields = $(".fieldEnabled").text();
            }
            fields = (fields == "null" ? "" : fields);
            if (fields) {
                fields = JSON.parse(fields);
                $.each(fields, function(key, value) {
                    if ($('[name="' + value + '[]"]').attr("type") == "checkbox") {
                        $('[name="' + value + '[]"]').attr("disabled", false);
                    } else {
                        $('[name="' + value + '"]').attr("disabled", false);

                        //show picklist if enabled
                        $('[name="' + value + '"]').closest(".setOBJ").find(".pickListButton").show();
                    }
                })
            }
        },
        fieldRequired: function() {
            var fields = ""
            var requestId = $("#ID").val();
            var requestor_id = $("#Requestor").val();
            var currentUser = $("#CurrentUser").val();
            if (requestor_id == currentUser || requestId == 0) {
                fields = $(".fieldRequired_default").text()

            } else {
                fields = $(".fieldRequired").text()
            }
            fields = (fields == "null" ? "" : fields);
            if (fields) {
                fields = JSON.parse(fields);
                $.each(fields, function(key, value) {
                    $('[name="' + value + '"]').attr("required", "required");
                })
            }
        },
        fieldHiddenValues: function() {
            var fields = ""
            var requestId = $("#ID").val();
            var requestor_id = $("#Requestor").val();
            var currentUser = $("#CurrentUser").val();
            if (requestor_id == currentUser || requestId == 0) {
                fields = $(".fieldHiddenValues_default").text()

            } else {
                fields = $(".fieldHiddenValues").text()
            }
            fields = (fields == "null" ? "" : fields);
            if (fields) {
                fields = JSON.parse(fields);
                $.each(fields, function(key, value) {
                    if ($('[name="' + value + '[]"]').attr("type") == "checkbox") {
                        $('[name="' + value + '[]"]').closest(".setOBJ").addClass("display2");
                    } else {
                        $('[name="' + value + '"]').closest(".setOBJ").addClass("display2");
                    }
                })
            }
        },
        setRepeaterContent: function() {
            var content = JSON.parse($('#Repeater_Data').val());

            console.log(content);
            for (var index = 0; index <= rowCount - 1; index++) {
                var fieldName = content[index].FieldName;
                var fieldContainer = $('[name="' + fieldName + '"]').closest('.input_position_below');

                var containerPanel = $(fieldContainer).closest('.setOBJ');
                var buttonContainer = $(containerPanel).closest('tr');

                $(buttonContainer).find('.rep-add-spec-row').each(function() {
                    if (index != 0) {
                        $(this).click();
                    }
                });
            }

            $('[repeater-table="true"]').find('tr').each(function(row) {
                $(this).find('.getFields ').each(function(column) {
                    var value = JSON.parse(content[column].Values);

                    switch ($(this).attr('type')) {
                        case "checkbox":
                            if ($(this).val() === value[row]) {
                                $(this).prop('checked', true);
                            } else {
                                $(this).prop('checked', false);
                            }
                            break;
                        case "radio":
                            break;
                        default :
                            break;
                    }

                    //$(this).val(value[row]);
                });
            });
        },
        getRepeaterContent: function() {
            var repeaters = [];
            $('[repeater-table="true"]').each(function() {
                $(this).find('tr:first').each(function() {
                    $(this).find('.getFields').each(function() {
                        var thisName = $(this).attr('name');
                        var data = [];
                        var fields = [];

                        $('[rep-original-name="' + thisName + '"], [name="' + thisName + '"]').each(function() {
                            var fieldType = $(this).attr('type');
                            var copyName = $(this).attr('name');
                            if (fields.indexOf(copyName) === -1) {
                                switch (fieldType) {
                                    case "checkbox":
                                        var addedValue = [];
                                        $('[name="' + copyName + '"]').each(function() {
                                            if ($(this).prop('checked')) {
                                                addedValue.push($(this).val());
                                            }
                                        });
                                        break;
                                    case "radio":
                                        var addedValue = [];
                                        $('[name="' + copyName + '"]').each(function() {
                                            if ($(this).prop('checked')) {
                                                addedValue.push($(this).val());
                                            }
                                        });
                                        break;
                                    default :
                                        var addedValue = $(this).val();
                                        break;
                                }

                                var valueGenerated = JSON.stringify(addedValue);

                                fields.push(copyName);
                                data.push(valueGenerated);
                            }
                        });

                        repeaters.push({
                            FieldName: thisName,
                            Data: data
                        });
                    });
                });
            });

            console.log(repeaters);
            $('#Repeater_Data').val(JSON.stringify(repeaters));
        },
        generateImportDialog: function() {
            $('body').on('click', '[link-type="import"]', function() {
                var formId = $(this).attr('link-form-id');
                var ret = '<form action ="/ajax/request_import" method="POST" enctype="multipart/form-data"> ' +
                        '<div style="float:left;width:50%;"><h3 class="pull-left fl-margin-bottom"><i class="icon-asterisk"></i> Request Import</h3></div>' +
                        '<div class="hr"></div>' +
                        '<input class="display" type="text" name="FormID" value = "' + formId + '" />' +
                        '<div class="fields"><div class="label_basic fl-margin-bottom">Please select file: </div><div class="input_position">' +
                        '<div id="uniform-fileInput" class="uploader">' +
                        '<input type="file" data-action-id="3" value="upload" name="fileupload" id="uploadForm" size="24" style="opacity: 0; width:100%;" class="import_request_file" />' +
                        '<span id="uploadFilename_3" class="filename import_request_txt">No file selected</span>' +
                        '<span class="action">Choose File</span>' +
                        '</div>' +
                        '</div></div>' +
                        '<div class="fields"><div class="label_basic"></div><div class="input_position" style="color:#ff0000;font-style:italic;margin-top:5px;">Note: File should be in Comma Separated Value(CSV) file format </div></div>' +
                        '<div class="fields"><div class="label_basic"></div><div class="input_position" style="margin-top:5px;"><input type="submit" class="btn-blueBtn fl-margin-right" value="Ok"> <input type="button" class="btn-basicBtn" id="popup_cancel" value="Cancel"></div></div>' +
                        ' </form>';
                jDialog(ret, '', '', '', '', function() {

                });
            });
        },
        // Print actual Form
        printForm: function() {
            var self = this;
            $("body").on("click", ".printForm", function() {
                $(".getFields").each(function() {
                    if ($(this).attr("type") == "radio") {
                        if ($(this).is(":checked")) {
                            $(this).attr("checked", "checked");
                        }
                    }
                })
                var pathname = window.location;
                if (getParametersName("view_type", pathname) == "preview") {
                    self.print_content("", "");
                } else {
                    var ret = '<h3 class="fl-margin-bottom"><i class="icon-print fa fa-print"></i> Print settings</h3>';
                    ret += '<div class="hr"></div>';
                    ret += '</div>';
                    ret += '<div id="comment-container" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; height: 100px;overflow: hidden;" class="ps-container">'
                    ret += '<div class="content-dialog sub-container-comment requestComment" style="width: 95%;height: auto;">';
                    ret += "<div style='font-weight: bold;margin-bottom: 10px;' class='fl-margin-top'>Choose data you want to include in your printing.</div>";
                    ret += '<div style="margin-left:10px">';
                    ret += "<label style=''><input type='checkbox' class='print-setting-inc css-checkbox' value='comment' id='print-setting-inc_comment'><label for='print-setting-inc_comment' class='css-label'></label> Comments</label><br /><br />";
                    ret += "<label style=''><input type='checkbox' class='print-setting-inc css-checkbox' value='audit-log' id='print-setting-inc_audit-logs'><label for='print-setting-inc_audit-logs' class='css-label'></label> Audit Logs</label>";
                    ret += '</div>';
                    ret += '</div>';
                    ret += '</div>';
                    ret += '<div class="fields">';
                    ret += '<div class="label_basic"></div>';
                    ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
                    ret += ' <input type="button" class="btn-blueBtn fl-margin-right" id="print-setup" value="Print" style="margin-left:5px; margin-bottom:5px;">';
                    ret += ' <input type="button" class="btn-basicBtn" id="popup_cancel" value="Close">';
                    ret += '</div>';
                    ret += '</div>';
                    var newDialog = new jDialog(ret, "", "", "500", "", function() {

                    });
                    newDialog.themeDialog("modal2");
                    $("#print-setup").click(function() {
                        var arrChecked = array_store(".print-setting-inc", "checkbox");
                        self.getLogs(function(logs) {
                            self.getComments(function(comments) {
                                if (arrChecked.indexOf("comment") == -1) {
                                    comments = "";
                                }
                                if (arrChecked.indexOf("audit-log") == -1) {
                                    logs = "";
                                }
                                self.print_content(logs, comments);
                            })
                        })

                    })
                }

                // $(".getFields").each(function() {
                //     if ($(this).attr("type") == "radio") {
                //         if ($(this).is(":checked")) {
                //             $(this).attr("checked", "checked");
                //         }
                //     }
                // })
                // var pathname = window.location;
                // if (getParametersName("view_type", pathname) == "preview") {
                //     self.print_content("", "");
                // } else {
                //     self.getLogs(function(logs) {
                //         self.getComments(function(comments) {
                //             self.print_content(logs, comments);
                //         })
                //     })
                // }

            });
        },
        print_content: function(logs, comments) {
            var ret = ""
            var widthForm = $(".preview_content").width();
            var heightForm = $(".preview_content").parent().height();
            var formName = $("#FormName").val();
            ret += '<link rel="stylesheet" type="text/css" href="/css/style.css" />';
            ret += '<link rel="stylesheet" type="text/css" href="/css/font-awesome.css" />';
            ret += '<link rel="stylesheet" type="text/css" href="/css/reset.css" />';
            ret += '<link rel="stylesheet" href="/css/jquery-ui.css" />';
            ret += '<link rel="stylesheet" href="/js/functions/formbuilder.css" />';


            var mywindow = window.open('', formName, 'height=' + heightForm + ',width=' + widthForm);
            mywindow.document.write('<html><head><title>' + formName + '</title>');
            $("link, style").each(function() {
                $(mywindow.document.head).append($(this).clone())
            });



            mywindow.document.write('</head><body>');
            mywindow.document.write('<div id="previewToPrint" style="height:auto">');
            mywindow.document.write('</div>');
            // mywindow.document.write($(".preview_content").clone(true)[0].outerHTML);
            var htmlClone = $(".preview_content").clone(true);
            $(htmlClone).appendTo(mywindow.document.getElementById("previewToPrint"));
            var selectIds = "";
            var select = "";
            var val = "";
            // console.log($(".preview_content").find("select .getFields").length)
            $(".preview_content").find("select").each(function() {
                if ($(this).hasClass("getFields")) {
                    selectIds = this.id;
                    val = $(this).val()
                    select = $(this).clone(true).val(val);
                    $(mywindow.document.getElementById(selectIds)).parent().html(select);
                }
            });


            if (logs != "") {
                mywindow.document.write("<div class='hr'></div>");
                mywindow.document.write(logs);
            }
            if (comments != "") {
                mywindow.document.write("<div class='hr'></div>");
                mywindow.document.write(comments);
            }

            mywindow.document.write('</body></html>');
            var tbWrapper = mywindow.document.getElementsByClassName("table-wrapper");
            var parentTbWrapper = "";
            for (var i in tbWrapper) {
                if (tbWrapper[i].style) {
                    tbWrapper[i].style.display = "block";
                }
                parentTbWrapper = tbWrapper[i].parentNode;
                if (parentTbWrapper) {
                    parentTbWrapper.style.overflow = "";
                }

            }
            var setObj = mywindow.document.getElementsByClassName("setOBJ");
            for (var i in setObj) {
                if (setObj[i].style) {
                    if (setObj[i].style.display != "none") {
                        setObj[i].style.display = "block";
                    }
                }
            }
            var fields_below = mywindow.document.getElementsByClassName("fields_below");
            for (var i in fields_below) {
                if (fields_below[i].style) {
                    if (fields_below[i].style.display == "table-cell") {
                        fields_below[i].style.display = "block";
                    }
                }
            }

            var display_form_status = mywindow.document.getElementsByClassName("display_form_status")
            if (display_form_status[0]) {
                display_form_status[0].style.display = "none";
            }
            // var select = mywindow.document.getElementsByTagName("select");
            // var classN = "";
            // for(var i in select){
            //     if(select[i].className){
            //         classN = select[i].className.split(" ");
            //         if(classN.indexOf("getFields")!=-1){
            //             mywindow.document.name(select[i].name).setAttribute("selected","selected");
            //         }
            //     }
            // }
            mywindow.print();
            mywindow.close();
        },
        getLogs: function(callback) {
            var request_id = $('#ID').val();
            var form_id = $('#FormID').val();
            //view of logs



            $.post('/ajax/getRequestLogs', {
                formId: form_id,
                request_Id: request_id
            }, function(data) {
                var result = JSON.parse(data);
                var ret = '<div><h3 class="fl-margin-bottom"><i class="icon-book fa fa-book"></i> Audit Logs</h3>';
                ret += '<div class="hr"></div>';
                ret += '<div id="logs-container" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; height: auto;" class="ps-container">'
                ret += '<div class="content-dialog sub-container-logs" style="width: 95%;">'
                for (var index in result) {
                    ret += '<div class="reply fl-padding-bottom " id="reply_80" style="width:100%;">';
                    // audit_table += '<a class="message-img" href="#">' + result[index].created_by.image + '</a>';
                    ret += '<div class="message-body" style="margin-left:0px;">';
                    ret += '<div class="text" id="postText_80" style="width: 94.4%; border: none!important;"><p>' + result[index].details + '</p></div>';
                    ret += '<p class="attribution">by <a href="#non">' + result[index].created_by.display_name + '</a> at <label class="timeago" title="' + result[index].date_created + '">' + result[index].date_created + '</label>';
                    ret += '</p></div>';
                    ret += '</div>';
                }
                ret += '</div>';
                ret += '</div>';
                ret += '</div>';
                callback(ret);
                //$("label.timeago").timeago();
            });
        },
        getComments: function(callback) {
            //view of comment
            $(".load-mr").show();
            var reqID = $("#ID").val();
            var formID = $("#FormID").val();
            $.ajax({
                type: "POST",
                url: "/ajax/post",
                dataType: "json",
                cache: false,
                data: "action=getComment" + "&postID=" + reqID + "&formID=" + formID,
                success: function(result) {
                    var ret = '';
                    if (result) {
                        ret = '<div><h3><i class="icon-comment"></i> Comments / Suggestion</h3>';
                        ret += '<div class="hr"></div>';
                        ret += '<div id="comment-container" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; height: auto;" class="ps-container">'
                        ret += '<div class="content-dialog sub-container-comment requestComment" style="width: 95%;height: auto;">';
                        for (var a = 0; a < result.length; a++) {
                            var postDetails = "print";
                            var uploadedDetails = null;
                            var likeDetails = null;
                            var comments = result[a];
                            ret += replyPost(postDetails, uploadedDetails, likeDetails, comments);
                        }
                        ret += '</div>';
                        ret += '</div>';
                        ret += '</div>';
                    }
                    callback(ret)
                }
            });
        },
        /* Remove Files attached on the request
         ================================================== */
        removeFiles: function() {
            $("body").on("click", ".removeFiles", function() {
                var self = $(this);
                var filename = $(this).attr("data-file");
                var file_location = $(this).attr("data-location");
                con = "Are you sure do you want to delete this?";
                var newConfirm = new jConfirm(con, 'Confirmation Dialog', '', '', '', function(r) {
                    if (r == true) {
                        $.post("/ajax/files", {action: "deleteFiles", filename: filename, file_location: file_location}, function(e) {

                            if (e == "File was successfully deleted.") {
                                self.parent().parent().parent().remove();
                            }
                        });
                    }
                });
                newConfirm.themeConfirm("confirm2", {'icon':'<i class="fa fa-exclamation-triangle fl-margin-right" style="color:#f00; font-size:15px;"></i>'});
            });
        },
        addViewer: function() {
            var requestId = $("#ID").val();
            var form_id = $('#FormID').val();
            var self = this;
            $("body").on("click", ".addViewer", function() {
                //add viwer
                var ret = '<h3 class="fl-margin-bottom"><i class="icon-book fa fa-user"></i> Add Viewer</h3>';
                ret += '<div class="hr"></div>';
                ret += '<div style="margin-bottom: 10px; margin-top:10px;padding:5px;/* font-style: italic; */font-size: 11px;"><span style="';
                ret += 'color: red;';
                ret += 'font-size: 13px;';
                ret += '">Note:</span> Only the users in the category where this form belongs to, are allowed to tag. Click <a id="seeAllUsers_AddViewers" style="cursor:pointer">SEE ALL</a> for allowed users to tag.</div>';
                ret += '</div>';
                ret += '<div id="add-viewer-container" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; height: 300px;overflow: hidden;" class="ps-container">'
                ret += '<div class="content-dialog sub-container-add-viewer" style="width: 95%;height: auto;">'
                ret += '<center><img src="/images/loader/loader.gif" class="load-mr" style="display: inline;margin-top:20%;"></center>'
                //ret += '<textarea class="mention display" id="mention-name" placeholder="" data-mentions-input="true" style="height: 42px;background-transparent"></textarea>';
                ret += '</div>'
                ret += '</div>'
                ret += '<div class="fields">';
                ret += '<div class="label_basic"></div>';
                ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
                ret += ' <input type="button" class="btn-basicBtn fl-margin-right" id="popup_cancel" value="Close" style="margin-bottom:5px;">';
                ret += ' <input type="button" class="btn-basicBtn fl-buttonEffect saveViewer fl-margin-right" value="Save" style="margin-bottom:5px;">';
                ret += '</div>';
                ret += '</div>';
              var newDialog = new  jDialog(ret, "", "", "", "", function() {
                });
              newDialog.themeDialog("modal2");
                // $(".sub-container-add-viewer").perfectScrollbar();

                //         $.post("/ajax/request_viewer",{action:"getUsers"},function(data){
                //             data = JSON.parse(data);
                // $(".sub-container-add-viewer").html('<textarea class="mention" id="mention-name" placeholder="" data-mentions-input="true" style="height: 42px;background-transparent"></textarea>')
                //             $("#mention-name").mention_only({
                //                 json : data

                //             });
                //         })
                if (requestId != 0) {
                    var returnViewer = "";
                    $.post("/ajax/request_viewer", {action: "getRequestViewer", request_id: requestId, form_id: form_id}, function(data) {
                        data = JSON.parse(data);
                        for (var i in data) {
                            returnViewer += "<div class='mentionSelected' data-id=" + data[i]['id'] + "><i class='removeTagg_i icon-remove-sign' style='margin-right: 5px;cursor: pointer;'></i>" + data[i]['name'] + "</div>";
                        }
                        $(".sub-container-add-viewer").html('<textarea class="mention" id="mention-name" placeholder="" data-mentions-input="true" style="height: 42px;background-transparent;border: transparent !important;"></textarea>')
                        $("#mention-name").mention_only({
                            json: data_name

                        });
                        $(".mention").before(returnViewer);
                    })
                }
                self.saveViewer();
            })
        },
        seeAllUsers_AddViewers: function() {
            var form_id = $('#FormID').val();
            $("body").on("click", "#seeAllUsers_AddViewers", function() {
                var mywindow = window.open("/ajax/request_viewer?seeAllUsersAddViewers=1&form_id=" + form_id + "", "", "width=350,height=500");
                // console.log($(mywindow.document.body).html());
                // $(mywindow.document.head).append('<link rel="stylesheet" type="text/css" href="/css/mention.css">')
            })
        },
        saveViewer: function() {
            var array_search = new Array();
            var requestId = $("#ID").val();
            var form_id = $('#FormID').val();
            $(".saveViewer").click(function() {
                ui.block()
                $(".mentionSelected").each(function() {
                    array_search.push($(this).attr("data-id"));
                })
                if (array_search.length == 0) {
                    showNotification({
                        message: "Please enter alteast 1 user",
                        type: "error",
                        autoClose: true,
                        duration: 3
                    });
                    ui.unblock()
                    return;
                }
                if (requestId != 0) {
                    //save to database
                    $.post("/ajax/request_viewer", {action: "saveViewer", array_search: array_search, requestId: requestId, form_id: form_id}, function(data) {
                        ui.unblock()
                        showNotification({
                            message: "Viewer Saved",
                            type: "success",
                            autoClose: true,
                            duration: 3
                        });
                        $("#popup_cancel").click();
                        array_search = [];
                    })
                } else {

                }
            })
        },
        getUserViewer: function() {
            var requestId = $("#ID").val();
            var form_id = $('#FormID').val();
            var self = this;
            $.post("/ajax/request_viewer", {action: "getTaggedUsers", requestId: requestId, form_id: form_id}, function(data) {
                if (data == 1) {
                    // $(".viewer_action").append('<button class="btn-basicBtn padding_5 cursor tip removetagRequest" data-original-title="Remove Tag"><i class="icon-power-off"></i></button>')
                    $(".viewer_action").append('<div class="fl-createViewreq fl-buttonEffect btn-basicBtn padding_5 cursor tip removetagRequest" data-original-title="Remove Tag" data-placement="bottom"><i class="fa fa-power-off"></i></div>');
                    $(".tip").tooltip();
                    self.removetagRequest();
                }
            })
        },
        removetagRequest: function() {
            var requestId = $("#ID").val();
            var form_id = $('#FormID').val();
            var self = this;
            $(".removetagRequest").click(function() {
                var newConf = new jConfirm('Are you sure you want to remove Tag?', '', '', '', '', function(r) {
                    if (r) {
                        // if ($('body').children(".submit-overlay").length == 0) {
                        //     var submit_overlay = $('<div class="submit-overlay" style="background:url(/images/loader/loader.gif);z-index: 100000;background-repeat:no-repeat;background-attachment:fixed;background-color:rgba(200,200,200,0.5);background-position:center;position:fixed;width:100%;height:100%;text-align:center;vertical-align:middle;">Loading...</div>');
                        //     $('body').prepend(submit_overlay);
                        // }
                        ui.block();
                        $.post("/ajax/request_viewer", {action: "removetagRequest", requestId: requestId, form_id: form_id}, function(data) {
                            showNotification({
                                message: "Tagged Removed",
                                type: "success",
                                autoClose: true,
                                duration: 3
                            });
                            ui.unblock()
                            $("#popup_cancel").click();
                            // $(".removetagRequest").remove();
                            // $(".tooltip").remove();
                            if(data==0){
                                setTimeout(function() {
                                    window.location = "/user_view/home";
                                }, 2000)
                            }
                        })
                    }
                });
                newConf.themeConfirm("confirm2", {'icon':'<i class="fa fa-exclamation-triangle fl-margin-right" style="color:#f00; font-size:15px;"></i>'});
            })
        },
        getButtons: function() {
            var buttons = ($('#LastAction').val() === undefined || $('#LastAction').val() === '') ? "" : JSON.parse($('#LastAction').val());
            var workflowId = $('#WorkflowId').val();
            var currentUser = $("#CurrentUser").val();
            var processor = $("#Processor").val();
            var requestId = $("#ID").val();
            var requestor_id = $("#Requestor").val();
            //$('#actionRequestButton').html('<option value="0">-------------Select Button-------------</option>');
            $('#fl-action-option').html('');
            if (!processor) {
                return;
            }
            processor = processor.split(",");
            if (processor.indexOf(currentUser) >= 0) {
                for (var index in buttons) {
                    //$('#actionRequestButton').append('<option value="' + buttons[index].button_name + '" data-workflow-id="' + workflowId + '" action="' + buttons[index].child_id + '">' + buttons[index].button_name + '</option>');
                    //<ul id="fl-action-option" style="z-index:1;"></ul>
                    $('#fl-action-option').append('<li class="fl-action-submit" value="' + buttons[index].button_name + '" data-workflow-id="' + workflowId + '" action="' + buttons[index].child_id + '" message="' + buttons[index].message + '"><a href="#" data-original-title="" title="">' + buttons[index].button_name + '</a></li>');
                }

                if (requestId != '0' && buttons != null) {
                    //$('#actionRequestButton').append('<option value="Save" data-workflow-id="Save" action="Save">Save</option>');
                    if($('[data-workflow-id="Save"]').length==0){
                        $('#fl-action-option').append('<li class="fl-action-submit" value="Save" data-workflow-id="Save" action="Save" message="Are you sure you want save this request?"><a href="#" data-original-title="" title="">Save</a></li>');
                    }
                    $(".tip").tooltip();
                }
            }

            var editors = String($("#Editor").val()).split(',');
            if (editors.indexOf(currentUser) >= 0) {
                if (requestId != '0' && buttons != null) {
                    //$('#actionRequestButton').append('<option value="Save" data-workflow-id="Save" action="Save">Save</option>');
                    if($('[data-workflow-id="Save"]').length==0){
                        $('#fl-action-option').append('<li class="fl-action-submit" value="Save" data-workflow-id="Save" action="Save" message="Are you sure you want save this request?"><a href="#" data-original-title="" title="">Save</a></li>');
                    }
                    $(".tip").tooltip();
                }
            }

            if (requestId != '0' && buttons != null) {
                if (requestor_id == currentUser) {
                    // $('#actionRequestButton').append('<option value="Cancel" data-workflow-id="Cancel" action="Cancel">Cancel</option>');
                    $('#fl-action-option').append('<li class="fl-action-submit" value="Cancel" data-workflow-id="Cancel" action="Cancel" message="Are you sure you want cancel this request?"><a href="#" data-original-title="" title="">Cancel</a></li>');

                }
            }
            if (processor.indexOf(currentUser) >= 0 || requestor_id == currentUser) {
                $(".viewer_action").append('<div class="fl-createViewreq fl-buttonEffect btn-basicBtn padding_5 cursor tip addViewer" data-original-title="Add Viewer" data-placement="bottom"><i class="fa fa-user icon-user"></i></div>')
                $(".tip").tooltip();
                var form_id = $('#FormID').val();
                $.post("/ajax/request_viewer", {action: "getRequestUsers", "form_id": form_id}, function(data) {
                    // console.log(data)
                    data_name = JSON.parse(data);
                })
                // $(".viewer_action").html('<button class="btn-basicBtn padding_5 cursor tip form-readers" data-original-title="Viewers"><i class="icon-book"></i></button>');
            }
            if ($("#fl-action-option").children("li").length == 0) {
                $("#fl-action-btn").css("display", "none");
            }
        },
        "makeRepeaterTable": function(tableElement, callBack) {
            var self_ini = this;
            try {
                if (typeof callBack == "undefined") {
                    //do nothing just catch errs
                }
            } catch (errs) {
                console.log(errs)
            }

            var repeat_fields = ".setObject";
            var table_body = $(tableElement).children("tbody");
            var table_row = table_body.children("tr");
            //MAG LALAGAY MUNA NG BUTTON ADDING SA BAWAT ROW
            //at initial startup
            //adding buttons
            table_row.each(function(eqi_tr) {
                td_ele = $(this).children("td");
                // relative_content = td_ele.last()/*.eq(0)*/.children(".td-relative");
                relative_content = td_ele.eq(0).children(".td-relative");
                $(this).addClass("original-row"); //declaring original row
                $(this).children("td").attr("row-height", $(this).outerHeight());
                relative_content.append(adding_and_removing_btn = $(
                        '<span class="repeater-action" style="opacity:0;z-index:2;position:absolute;bottom:0px;">' +
                        '<a class="fa fa-plus icon-plus rep-add-spec-row" style="width:auto;height:auto;margin: 0px 5px;"></a>' +
                        '<a class="fa fa-minus icon-minus rep-remove-spec-row" style="width:auto;height:auto;margin: 0px 5px;"></a>' +
                        '</span>'
                        ));
                //don't display remove row on original buttons
                adding_and_removing_btn.children(".rep-remove-spec-row").eq(0).css({
                    "display": "none"
                });
                // adding_and_removing_btn.css({
                //    // "margin-left":"-"+(adding_and_removing_btn.css("width")),
                //    "margin-right":"-"+(adding_and_removing_btn.css("width")),
                //    "position":"absolute",
                //    "right":"0px"
                // });
                adding_and_removing_btn.css({
                    // "margin-left":"-"+(adding_and_removing_btn.css("width")),
                    "left": "0px"
                });
                //adding events for button
                evRepeaterAdd(adding_and_removing_btn);
                evRepeaterRemove(adding_and_removing_btn);

                //adding events for button version 2
                // evRepeaterAddV2(adding_and_removing_btn);
                // evRepeaterRemoveV2(adding_and_removing_btn);
            });

            //functionality event
            {//OLD VERSION SLOW
                function evRepeaterAdd(repeaterBtnEle) {
                    if (repeaterBtnEle.children(".rep-add-spec-row").length >= 1) {
                        repeaterBtnEle.children(".rep-add-spec-row").on({
                            "click": function(e) {
                                var select_dis_table = $(this).parents("table.form-table");
                                if (select_dis_table.data("added_rows_uid")) {
                                    select_dis_table.data("added_rows_uid", (select_dis_table.data("added_rows_uid") + 1));
                                } else {
                                    select_dis_table.data("added_rows_uid", 1);
                                }
                                e.preventDefault();
                                var pathname = window.location;

                                if ($(this).closest("tr.original-row").length >= 1) {
                                    //repeat clicked row, append content
                                    var appended_row = "";
                                    $(this).closest("tr.original-row").after(appended_row = $(
                                            '<tr>' +
                                            $(this).closest("tr.original-row").html() +
                                            '</tr>'
                                            ));
                                    appended_row.children("td").slideUp(500).stop(true, true);
                                    appended_row.children("td").slideDown(500);
                                    var rep_btn_container_ar = appended_row.children("td").children(".td-relative").children(".repeater-action");
                                    //display the remove row button of the repeated row
                                    rep_btn_container_ar.children(".rep-remove-spec-row").css({
                                        "display": ""
                                    });
                                    rep_btn_container_ar.css({
                                        "left": "0px"
                                    });


                                    //adding event for original row button

                                    evRepeaterAdd(rep_btn_container_ar);
                                    evRepeaterRemove(rep_btn_container_ar);
                                    // rebindFieldFunctionality(appended_row);
                                    rebindFieldFunctionalityV3.call($(this),appended_row);
                                } else {
                                    //repeat clicked row, append content
                                    var appended_row = "";
                                    $(this).closest("tr").after(appended_row = $(
                                            '<tr>' +
                                            $(this).closest("tr").html() +
                                            '</tr>'
                                            ));
                                    appended_row.children("td").slideUp(500).stop(true, true);
                                    appended_row.children("td").slideDown(500);
                                    var rep_btn_container_ar2 = appended_row.children("td").children(".td-relative").children(".repeater-action");
                                    //display the remove row button of the repeated row
                                    rep_btn_container_ar2.children(".rep-remove-spec-row").css({
                                        "display": ""
                                    });
                                    rep_btn_container_ar2.css({
                                        // "margin-left":"-"+(rep_btn_container_ar2.css("width")),
                                        "left": "0px"
                                    });

                                    //adding event for original row button
                                    evRepeaterAdd(rep_btn_container_ar2);
                                    evRepeaterRemove(rep_btn_container_ar2);
                                    // rebindFieldFunctionality(appended_row);
                                    rebindFieldFunctionalityV3.call($(this),appended_row);
                                }
                                // refreshRepeaterTable($(this).closest(".form-table"));
                                // rebindFieldFunctionality(appended_row); // MAY PROBLEMS PA SA NAMES BIND
                                // rebindFieldFunctionalityV2($(this).closest(".form-table"));
                                // console.log($(this),"TABLE ADD ??",dis_appended_row,dis_appended_row.index());
                                if($(this).parents("[table-response-to]").eq(0).length >= 1){
                                    var clicked_row_index = $(this).parents("tr").eq(0).index();
                                    var tables_affected = $(this).parents("[table-response-to]").attr("table-response-to").split(",");
                                    var collect_selection = null;
                                    for(var ii = 0 ; ii < tables_affected.length ; ii ++){
                                        if(ii== 0 && collect_selection == null){
                                            collect_selection = $("[table-name='"+tables_affected[ii]+"']");
                                        }else{
                                            // console.log("NAKITA",$("[table-name='"+tables_affected[ii]+"']"))
                                            collect_selection = collect_selection.add($("[table-name='"+tables_affected[ii]+"']"));
                                        }
                                    }
                                    console.log("TRIPPIN",collect_selection)
                                    collect_selection.each(function(eqi){
                                        if($(this).find("tbody").children("tr").eq(clicked_row_index).length >= 1){
                                            $(this).find("tbody").children("tr").eq(clicked_row_index).find(".rep-add-spec-row").eq(0).trigger("click");
                                        }
                                    })
                                }
                                return false;
                            }
                        });
                    }
                }
                function rebindFieldFunctionality(appended_row) { // defaultComputed(data_obj_id,the_field_ele,this_element,eventAddressNamespace){
                    if (appended_row.find(".hasDatepicker").length >= 1) {
                        appended_row.find(".hasDatepicker").each(function() {
                            $(this).removeClass("hasDatepicker");
                            if ($(this).attr("data-type")) {
                                if ($(this).attr("data-type") == "date") {
                                    $(this).datepicker({
                                        'dateFormat': 'yy-mm-dd'
                                    });

                                } else if ($(this).attr("data-type") == "dateTime") {
                                    $(this).datetimepicker({
                                        'dateFormat': 'yy-mm-dd'
                                    });
                                }
                            }
                        });
                    }
                    appended_row.find(".setObject").each(function() {

                    });
                }
                function rebindFieldFunctionalityV2(table) {
                    var table_id = table.closest(".setOBJ").attr("data-object-id");
                    table.find(".hasDatepicker").each(function(eqi) {
                        // console.log($(this).data())
                        // console.log(typeof $(this).data().datepicker);
                        //DESTROY HERE
                        if ($(this).data().datepicker) {
                            $(this).datepicker("destroy");
                        }
                        //REBIND HERE
                        if (typeof $(this).data().datepicker == "undefined") {
                            $(this).removeClass("hasDatepicker");
                            if ($(this).attr("data-type")) {
                                if ($(this).attr("data-type") == "date") {
                                    $(this).datepicker({
                                        'dateFormat': 'yy-mm-dd'
                                    });
                                } else if ($(this).attr("data-type") == "dateTime") {
                                    $(this).datetimepicker({
                                        'dateFormat': 'yy-mm-dd'
                                    });
                                }
                            }
                        }
                    });
                    // console.log("STARTING... REBINDING OF COMPUTED DEFAULT VALUE FIELDS LIST THEN");

                    //destroy first
                    $(".getFields").off("change.repeaterDefaultValueComputed" + table_id);
                    $(".getFields").off("keyup.repeaterDefaultValueComputed" + table_id);
                    //"startUpDefaultValComputed"
                    //makeOnChange(fieldAffected,fieldWithComputation,eventAddressNamespace)
                    table.children("tbody").children("tr").each(function(eqi_tr) {
                        $(this).find(".setOBJ").each(function(eqi_setOBJ) {
                            var obj_id = $(this).attr("data-object-id");
                            var this_setOBJFIELD = $(this).find(".getFields_" + obj_id);
                            // console.log("REFRESH")
                            // console.log(this_setOBJFIELD)
                            var this_setOBJFIELD_name = this_setOBJFIELD.eq(0).attr("name");
                            if (this_setOBJFIELD.data("events")) {
                                if (this_setOBJFIELD.data("events").change) {
                                    for (var ctr = 0; ctr < this_setOBJFIELD.data("events").change.length; ctr++) {
                                        if (this_setOBJFIELD.data("events").change[ctr].namespace.toLowerCase().indexOf("startup") >= 0) {
                                            return true;
                                        }
                                    }
                                }
                            }

                            if (this_setOBJFIELD.data("events")) {
                                if (this_setOBJFIELD.data("events").keyup) {
                                    for (var ctr = 0; ctr < this_setOBJFIELD.data("events").keyup.length; ctr++) {
                                        if (this_setOBJFIELD.data("events").keyup[ctr].namespace.toLowerCase().indexOf("startup") >= 0) {
                                            return true;
                                        }
                                    }
                                }
                            }

                            if (this_setOBJFIELD.attr("default-type")) { //PA ROW NORMAL lANG
                                if (this_setOBJFIELD.attr("default-type") == "computed") {
                                    //REBIND DEFAULT VALUES COMPUTED
                                    //console.log("REFRESh");
                                    //console.log(this_setOBJFIELD);
                                    self_ini.defaultComputed(obj_id, this_setOBJFIELD, this, "repeaterDefaultValueComputed" + table_id);
                                    // console.log( this_setOBJFIELD.parents(".setOBJ").eq(0) )
                                }
                            }
                            //console.log("arrgh")
                            //console.log(this_setOBJFIELD)
                            if (typeof this_setOBJFIELD.attr("event-id-from") != "undefined") { //PACOLUMN FORMULA IS AT OUTER @fieldName[sum]
                                var ids = this_setOBJFIELD.attr("event-id-from").split(",");
                                var idEleWithFormula = "";
                                for (var zz = 0; zz < ids.length; zz++) {
                                    var idEleWithFormula = $(".getFields_" + ids[zz]);
                                    self_ini.makeOnChange(this_setOBJFIELD, idEleWithFormula, "repeaterDefaultValueComputed" + table_id);
                                }
                                // var idEleWithFormula = $(".getFields_" + this_setOBJFIELD.attr("event-id-from"));
                                // console.log("GEH NGA??")
                                // console.log(this_setOBJFIELD)
                                // makeOnChange(this_setOBJFIELD, idEleWithFormula, "repeaterDefaultValueComputed" + table_id);
                            }

                            //CURRENCY FORMAT
                            if (this_setOBJFIELD.attr("data-input-type") == 'Currency') {
                                var has_change_curr_format = false;
                                var data_events = this_setOBJFIELD.data("events");
                                if (typeof data_events != "undefined") {
                                    if (typeof data_events["change"] != "undefined") {
                                        $.each(this_setOBJFIELD.data("events")["change"], function(index, value) {
                                            if (value["namespace"] == "currency_format") {
                                                has_change_curr_format = true;
                                                return false;
                                            }
                                        });
                                    }
                                }
                                if (has_change_curr_format == false) {
                                    this_setOBJFIELD.on("change.currency_format", function() {
                                        if ($.isNumeric($(this).val())) {
                                            var value_number = parseFloat($(this).val());
                                            $(this).val(value_number.currencyFormat());
                                        } else {
                                            var value_nito = $(this).val()
                                            var sanitized_val = value_nito.replace(/[\s,]/g, "");
                                            if ($.isNumeric(sanitized_val)) {
                                                var value_number = parseFloat(sanitized_val);
                                                $(this).val(value_number.currencyFormat());
                                            }
                                        }
                                    });
                                }
                            }


                        });
                    });
                    table.find(".getFields").change();
                }

                function rebindFieldFunctionalityV3(appended_row) {
                    var select_tbody = $(appended_row).parents("tbody").eq(0);
                    // var count_trs = select_tbody.children("tr").length;
                    var count_trs = select_tbody.parents("table.form-table").data("added_rows_uid");
                    var dis_appended_row = $(appended_row);
                    var table_id = dis_appended_row.parents("table.form-table").eq(0).parents(".setOBJ").eq(0).attr("data-object-id");

                    //remove class
                    dis_appended_row.find(".hasDatepicker").removeClass("hasDatepicker");

                    //remove attr's
                    dis_appended_row.find("[value]").not('OPTION,[type="radio"],[type="checkbox"]').removeAttr("value");

                    //fixing ids and names
                    dis_appended_row.find("[data-object-id]").each(function(eq_name) {//FIX IDS
                        if ($(this).attr("rep-data-doi")) { //REPLACING THE GETFIELD UNIQUE CLASS
                            var doi = $(this).attr("rep-data-doi");
                            var getFields = $(this).find("*").filter(function() {
                                var regu_eks = new RegExp("getFields_" + doi, "g");
                                return regu_eks.test($(this).attr("rep-data-class"));
                            });

                            $(this).attr("data-object-id", $(this).attr("rep-data-doi") + "_UID" + count_trs);

                            if (getFields.attr("rep-data-class")) {
                                var reg_eks = new RegExp("getFields_[0-9]*", "g");
                                var replaced_class = getFields.attr("rep-data-class").replace(reg_eks, "getFields_" + doi + "_UID" + count_trs);
                                getFields.attr("class", replaced_class);
                            }
                        } else { //REPLACING THE UNIQUE GETFIELD CLASS
                            $(this).attr("rep-data-doi", $(this).attr("data-object-id"));
                            $(this).attr("data-object-id", $(this).attr("data-object-id") + "_UID" + count_trs);
                            var new_doi = $(this).attr("rep-data-doi");
                            var getFields = $(this).find(".getFields_" + new_doi);
                            var reg_eks = new RegExp("getFields_[0-9]*", "g");
                            getFields.attr("rep-data-class", getFields.attr("class"));
                            var replaced_class = getFields.attr("class").replace(reg_eks, "getFields_" + new_doi + "_UID" + count_trs);
                            getFields.attr("class", replaced_class);
                        }
                    });

                    dis_appended_row.find("[id]").each(function(eq_id) {//FIX IDS
                        if ($(this).attr("rep-data-id")) {
                            $(this).attr("id", $(this).attr("rep-data-id") + "_UID" + count_trs);
                        } else {
                            $(this).attr("rep-data-id", $(this).attr("id"));
                            $(this).attr("id", $(this).attr("id") + "_UID" + count_trs);
                        }
                    });
                    dis_appended_row.find("[name]").each(function(eq_name) {//FIX IDS
                        if ($(this).attr("rep-original-name")) {
                            $(this).attr("name", $(this).attr("rep-original-name") + "_UID" + count_trs);
                        } else {
                            $(this).attr("rep-original-name", $(this).attr("name"));
                            $(this).attr("name", $(this).attr("name") + "_UID" + count_trs);
                        }
                    });




                    //restoring functionality
                    {
                        //DATEPICKER
                        dis_appended_row.find('input[data-type="date"]').each(function(eq_d) {
                            $(this).datepicker({
                                'dateFormat': 'yy-mm-dd'
                            });
                            if (ThisDate($(this).val()) != "Invalid Date") {
                                $(this).val(ThisDate($(this).val()).formatDate("Y-m-d"));
                            }
                        })
                        //DATETIMEPICKER
                        dis_appended_row.find('input[data-type="dateTime"]').each(function(eq_d) {
                            $(this).datetimepicker({
                                dateFormat: 'yy-mm-dd'
                            });
                            if (ThisDate($(this).val()) != "Invalid Date") {
                                $(this).val(ThisDate($(this).val()).formatDate("Y-m-d H:i"));
                            }
                        })
                        //TIME
                        dis_appended_row.find('input[data-type="time"]').each(function(eq_d) {
                            $(this).datetimepicker({
                                dateFormat: '',
                                timeFormat: 'HH:mm',
                                timeOnly: true
                            });
                            if (!$(this).val() && $(this).val().length >= 1) {
                                var time_val = ThisDate(ThisDate(new Date()).formatDate("Y-m-d") + " " + $(this).val());

                                if (time_val != "Invalid Date") {
                                    $(this).val(time_val.formatDate("H:i"));
                                }
                            }

                        })
                        //CURRENCY
                        dis_appended_row.find(".getFields[data-input-type='Currency']").each(function() {
                            $(this).on("change.currency_format", function() {
                                if ($.isNumeric($(this).val())) {
                                    var value_number = parseFloat($(this).val());
                                    $(this).val(value_number.currencyFormat());
                                } else {
                                    var value_nito = $(this).val()
                                    var sanitized_val = value_nito.replace(/[\s,]/g, "");
                                    if ($.isNumeric(sanitized_val)) {
                                        var value_number = parseFloat(sanitized_val);
                                        $(this).val(value_number.currencyFormat());
                                    }
                                }
                            })
                            $(this).change();
                        });
                        //REPEATER ACTION BUTTON DISABLING
                        dis_appended_row.on({
                            "mouseenter": function(e) {
                                if (!$(this).find(".repeater-action").hasClass("disable-repeater-action")) {
                                    $(this).find(".repeater-action").css("display", "");
                                    $(this).find(".repeater-action").stop(false, false).animate({
                                        "opacity": 1
                                    }, function() {
                                        //TEST
                                    })
                                }
                            },
                            "mouseleave": function(e) {
                                $(this).find(".repeater-action").stop(false, false).animate({
                                    "opacity": 0
                                }, function() {
                                    $(this).css("display", "none");
                                })
                            }
                        })
                        {//DISABLING REPEATER ACTION BUTTON BASED OF DISABLED FIELDS
                            var total_field_disabled_in_row = dis_appended_row.find(".getFields:disabled").length;
                            var total_field_in_row = dis_appended_row.find(".getFields").length;
                            if (total_field_disabled_in_row == total_field_in_row) {
                                dis_appended_row.find(".repeater-action").addClass("disable-repeater-action");
                            }
                        }
						{//AUTO FIX FORMULA NAMES INDEXES IN ROW EXISTENCE
                            dis_appended_row.find('.getFields[default-type="computed"][default-formula-value]').each(function(){
                                var self = $(this);
                                var dis_formula = self.attr('default-formula-value');
                                var dis_formula_original = self.attr('default-formula-value');
                                if(self.attr('original-default-formula-value')){
                                    dis_formula = self.attr('original-default-formula-value');
                                    dis_formula_original = self.attr('original-default-formula-value');
                                }
                                var reg_eks_get_name = new RegExp("@[a-zA-Z][a-zA-Z0-9_]*","g");
                                var name_matches = dis_formula.match(reg_eks_get_name).filter(Boolean);
                                var collect_names = [];
                                var reg_eks_for_replace = null;
                                var function_keyword_names = [
                                    '@StrRight', '@StrLeft', '@StrCount', '@StrConcat',
                                    '@StrGet', '@ThisDate', '@AdjustDate', '@DiffDate',
                                    '@GivenIf', '@Lookup', '@RecordCount', '@LookupWhere',
                                    '@Total', '@LookupGetMax', '@LookupGetMin', '@LookupSDev',
                                    '@LookupAVG', '@GetRound', '@LookupCountIf','@Sum', 
                                    '@Requestor', '@RequestID', '@Status', '@CurrentUser', '@Department', '@TrackNo', '@Today', '@Now',
                                    '@GetAuth'
                                ];

                                
                                //console.log("name_matches",name_matches);
                                for(var iz in name_matches){
                                    if(function_keyword_names.indexOf(name_matches[iz]) < 0){
                                        collect_names.push({
                                            "origin_name":name_matches[iz],
                                            "modify_name":name_matches[iz]+"_UID"+count_trs,
                                        });
                                    }
                                }
                                for(var iz in collect_names){
                                    //console.log("origin_name",collect_names[iz]['origin_name'],"modify_name",collect_names[iz]['modify_name'], " "+dis_appended_row.find('[name="'+collect_names[iz]['modify_name'].replace("@","")+'"]').length)
                                    if(dis_appended_row.find('[name="'+collect_names[iz]['modify_name'].replace("@","")+'"]').length >= 1){
                                        reg_eks_for_replace = new RegExp(collect_names[iz]['origin_name']+"(?![a-zA-Z0-9_])","g")
                                        dis_formula = dis_formula.replace(reg_eks_for_replace, collect_names[iz]['modify_name']);
                                        //console.log(reg_eks_for_replace,"modified",dis_formula);
                                    }
                                }
                                //console.log('dis_formula',dis_formula);
                                self.attr('default-formula-value', dis_formula);
                                self.attr('original-default-formula-value', dis_formula_original);
                            })
                        }
                        //REBIND DEFAULT COMPUTED
                        dis_appended_row.find('.getFields[default-type="computed"][default-formula-value]').each(function() {
                            console.log("ELEMENT REPEATED W FORMULAS " + $(this).attr("name"), $(this));
                            var this_element_setOBJ = $(this).parents(".setOBJ").eq(0);
                            var this_element_field = $(this);
                            var data_obj_id = this_element_setOBJ.attr("data-object-id");

                            self_ini.defaultComputed(data_obj_id, this_element_field, this_element_setOBJ, "repeaterDefaultValueComputed" + table_id);
                        });
                        //REBIND FIELDS FROM COMPUTED FORMULAS
                        dis_appended_row.find('.getFields[event-id-from]').each(function(eqi) {

                            var edoi_from = $(this).attr("event-id-from");
                            var element_in_computation = $(this);
                            var splitted_edoi_from = edoi_from.split(",");

                            for (index_oid in splitted_edoi_from) {

                                var the_fields = $("[data-object-id='" + splitted_edoi_from[index_oid] + "']").find(".getFields_" + splitted_edoi_from[index_oid]);
                                if (the_fields.attr("default-formula-value")) {
                                    console.log("ID MAY FORMULA" + splitted_edoi_from[index_oid], the_fields.attr("name"), element_in_computation.attr("name"), "TBL ID::" + table_id)
                                    var eventAddressNamespace = "repeaterDefaultValueComputed" + table_id;
                                    self_ini.makeOnChange(element_in_computation, the_fields, eventAddressNamespace);
                                }
                            }

                        })
                        //TRIGGER CHANGES OF NEWLY ADDED ROW
                        dis_appended_row.find('.getFields').filter(function(index, element) {
                            var dis_ele = $(element);
                            var dis_ele_ev_data = dis_ele.data("events")
                            if (dis_ele_ev_data) {
                                if (dis_ele_ev_data["change"]) {
                                    if (dis_ele_ev_data["change"].length >= 1) {
                                        return true;
                                    }
                                }
                            }
                        }).change();

                        
                    }

                }

                function evRepeaterRemove(repeaterBtnEle) {
                    if (repeaterBtnEle.children(".rep-remove-spec-row").length >= 1) {
                        repeaterBtnEle.children(".rep-remove-spec-row").on({
                            "click": function(e) {
                                e.preventDefault();
                                if ($(this).attr("disabled")) {

                                } else {
                                    $(this).closest("tr").children("td").animate({
                                        "height": 0
                                    }, function() {
                                        var this_table = $(this).closest(".form-table");
                                        $(this).closest("tr").remove();
                                        this_table.find("tbody").eq(0).children("tr").eq(0).find(".getFields").filter(function(index, dom) { //UNANG ROW LANG ANG NAKA .CHANGE
                                            var dis_ele_dom = $(this)
                                            var ded_data_events = dis_ele_dom.data("events");
                                            if (ded_data_events["change"]) {
                                                if (ded_data_events["change"].length >= 1) {
                                                    return true;
                                                }
                                            }
                                            return false;
                                        }).change();
                                        // refreshRepeaterTable(this_table);
                                        // rebindFieldFunctionalityV2(this_table);
                                    });
                                }
                                if($(this).parents("[table-response-to]").eq(0).length >= 1){
                                    var clicked_row_index = $(this).parents("tr").eq(0).index();
                                    var tables_affected = $(this).parents("[table-response-to]").attr("table-response-to").split(",");
                                    var collect_selection = null;
                                    for(var ii = 0 ; ii < tables_affected.length ; ii ++){
                                        if(collect_selection == null){
                                            collect_selection = $("[table-name='"+tables_affected[ii]+"']")
                                        }else{
                                            collect_selection = collect_selection.add($("[table-name='"+tables_affected[ii]+"']"));
                                        }
                                    }
                                    collect_selection.each(function(eqi){
                                        if($(this).find("tbody").children("tr").eq(clicked_row_index).length >= 1){
                                            $(this).find("tbody").children("tr").eq(clicked_row_index).find(".rep-remove-spec-row").eq(0).trigger("click");
                                        }
                                    })
                                }
                                return false;
                            }
                        });
                    }
                }
                function refreshRepeaterTable(tableEle) {
                    var field_container = ".setOBJ";
                    var table_body = $(tableEle).children("tbody");
                    var table_row = table_body.children("tr");
                    $(table_row).each(function(eqi_tr_i) {
                        var total_field_disabled_in_row = $(this).find(".getFields:disabled").length;
                        var total_field_in_row = $(this).find(".getFields").length;
                        if (total_field_in_row == total_field_disabled_in_row) {
                            $(this).find(".repeater-action").css("opacity", 0);
                            $(this).find(".repeater-action").addClass("disable-repeater-action");
                            $(".disable-repeater-action").children(".rep-remove-spec-row,.rep-add-spec-row").attr("disabled", true);
                            $(".disable-repeater-action").children(".rep-remove-spec-row,.rep-add-spec-row").prop("disabled", true);
                        }
                        if ($(this).hasClass("original-row")) {
                            //
                        } else {
                            $(this).find(field_container).each(function() {
                                sobj_index_id = $(this).attr("data-object-id");
                                $(this).find(".getFields_" + sobj_index_id).each(function() {

                                    if (!$(this).attr("rep-original-id")) {
                                        $(this).attr("rep-original-id", $(this).attr("id"));
                                        $(this).attr("id", $(this).attr("rep-original-id") + "_tr" + eqi_tr_i);
                                    } else {
                                        //
                                        $(this).attr("id", $(this).attr("rep-original-id") + "_tr" + eqi_tr_i);
                                    }

                                    if (!$(this).attr("rep-original-name")) {
                                        $(this).attr("rep-original-name", $(this).attr("name"));
                                        $(this).attr("name", $(this).attr("rep-original-name") + "_tr" + eqi_tr_i);
                                    } else {
                                        //
                                        $(this).attr("name", $(this).attr("rep-original-name") + "_tr" + eqi_tr_i);
                                    }

                                    //MAKE AN INDEX TOO ON FORMULAS
                                    // if($(this).attr("default-type")){
                                    //    if($(this).attr("default-type") == "computed"){
                                    //      var computed_default_value = $(this).attr("default-formula-value");
                                    //      var splitted_default_val = computed_default_value.match(/@\(.*?\)|@[a-zA-Z0-9_]*/g);
                                    //      if(splitted_default_val != null){
                                    //            console.log("FIGURE THIS OUT")
                                    //            for(var ctr = 0 ; ctr < splitted_default_val.length ; ctr++){
                                    //                  var formula_key_words = new Array("@Department","@Status","@Requestor","@RequestID","@Now","@Today","@TrackNo","@CurrentUser","@StrRight","@StrLeft","@GivenIf");
                                    //                  var ele_in_formula = $('[name="'+splitted_default_val[ctr].replace("@","")+'"]');
                                    //                  if(ele_in_formula.length >= 1){
                                    //                        console.log(ele_in_formula.data("events"));
                                    //                        var ele_in_f_val = $.trim(ele_in_formula.val() );
                                    //                        if($.isNumeric(ele_in_f_val ) ){
                                    //                             computed_default_value = computed_default_value.replace(splitted_default_val[ctr], ele_in_f_val);
                                    //                        }else{
                                    //                             computed_default_value = computed_default_value.replace(splitted_default_val[ctr], "\""+ele_in_f_val+"\"");
                                    //                        }
                                    //                  }else{
                                    //                         if(formula_key_words.indexOf(splitted_default_val[ctr]) >= 0 ){
                                    //                            if(splitted_default_val[ctr] == "@Requestor"){
                                    //                                 requestor_ele = "<?php echo $auth['display_name']; ?>";
                                    //                                 computed_default_value = computed_default_value.replace(splitted_default_val[ctr],"\""+requestor_ele+"\"" );
                                    //                            }else if(splitted_default_val[ctr] == "@RequestID"){
                                    //                                 var value_reqID = $("#ID").val();
                                    //                                 computed_default_value = computed_default_value.replace(splitted_default_val[ctr], value_reqID);
                                    //                            }else if(splitted_default_val[ctr] == "@Department"){
                                    //                                 var value_reqID = $("[name='Department_Name']").val();
                                    //                                 computed_default_value = computed_default_value.replace(splitted_default_val[ctr], value_reqID);
                                    //                            }else if(splitted_default_val[ctr] == "@RowIndex"){

                                    //                                 if($(this).parents("tr").length >=1){
                                    //                                     var rowIndex_val = $(this).parents("tr").eq(0).index();
                                    //                                     computed_default_value = computed_default_value.replace(splitted_default_val[ctr], rowIndex_val);
                                    //                                 }
                                    //                            }
                                    //                            continue;
                                    //                          }else{
                                    //                            var toBeReplace = splitted_default_val[ctr];
                                    //                            var formula_RegExp = new RegExp("("+toBeReplace+"|"+toBeReplace+"_tr[0-9]*)","g");
                                    //                            computed_default_value = computed_default_value.replace(formula_RegExp, splitted_default_val[ctr].replace(/_tr[0-9]*/g,"")+"_tr"+eqi_tr_i);
                                    //                          }
                                    //                  }
                                    //            }
                                    //      }
                                    //      var status_ok = "false";
                                    //      try{
                                    //         eval(computed_default_value);
                                    //         status_ok = "true";
                                    //      }catch(eerr){

                                    //      }
                                    //      if(status_ok== "true"){
                                    //         $(this).val(eval(computed_default_value));
                                    //      }
                                    //    }
                                    // }
                                });

                                $(this).find(".pickListButton").each(function() {
                                    if (!$(this).attr("original-return-field")) {
                                        $(this).attr("original-return-field", $(this).attr("return-field"));
                                        $(this).attr("return-field", $(this).attr("original-return-field") + "_tr" + eqi_tr_i);
                                    } else {
                                        $(this).attr("return-field", $(this).attr("original-return-field") + "_tr" + eqi_tr_i);
                                    }
                                });
                            });
                        }
                    });
                    if (typeof callBack != "undefined") {
                        callBack(tableEle);
                    }
                }

                refreshRepeaterTable(tableElement); // this excute at the startup of repeater table ... so that the rows with no fields 
            }



            // {//eyAH NEW VERSION REPEATER TABLE FAST
            //     function evRepeaterAddV2(row_button){
            //         if (row_button.find(".rep-add-spec-row").length >= 1) {
            //             row_button.find(".rep-add-spec-row").eq(0).on("click",function(){
            //                 var tr_element = $(this).parents("tr").eq(0);
            //                 var tr_append_location = tr_element;
            //                 var tr_cloned = tr_element.clone();
            //                 tr_append_location.after(tr_cloned);
            //                 tr_cloned.find(".rep-remove-spec-row").css("display","");
            //             })
            //         }
            //     }
            //     function evRepeaterRemoveV2(row_button){
            //         if (row_button.find(".rep-remove-spec-row").length >= 1) {
            //             row_button.find(".rep-remove-spec-row").eq(0).on("click",function(){
            //                 alert("MAYNUS");
            //             })
            //         }
            //     }
            // }

            if (typeof callBack != "undefined") {
                callBack(tableElement);
            }
        },
        "getUpdatedServerTime": function() {
            var b_data = $("body").data();
            if (b_data) {
                if (b_data.getServerTimeData) {
                    return b_data.getServerTimeData;
                }
            }
            return "";
        },
        // "defaultComputed": function(data_obj_id, the_field_ele, this_element, eventAddressNamespace) {
        //     var this_ini_variant = this;
        //     the_field = the_field_ele;
        //     this_self_ele = $(this_element);
        //     var string_default_val = "" + $(this_self_ele).find(".getFields_" + data_obj_id).attr("default-formula-value");

        //     string_default_val = "" + $(this_self_ele).find(".getFields_" + data_obj_id).attr("default-formula-value");

        //     if (string_default_val.indexOf("@Lookup") >= 0) {
        //         return;
        //     }

        //     if (string_default_val.indexOf("@RecordCount") >= 0) {
        //         return;
        //     }
        //     if (string_default_val.indexOf("@LookupWhere") >= 0) {
        //         return;
        //     }
        //     if (string_default_val.indexOf("@AVG") >= 0) {
        //         return;
        //     }
        //     if (string_default_val.indexOf(/^@Total\(*.\)$/) >= 0) {
        //         return;
        //     }

        //     splitted_default_val = string_default_val.match(/@GetAVG\(@[A-Za-z0-9_]*\)|@SDev\(@[A-Za-z0-9_]*\)|@GetMin\(@[A-Za-z0-9_]*\)|@GetMax\(@[A-Za-z0-9_]*\)|@Sum\(@[A-Za-z0-9_]*\)|@[a-zA-Z0-9_]*\[[A-Za-z]*\]|@[a-zA-Z0-9_]*/g);
        //     console.log("HEY", splitted_default_val)

        //     if (splitted_default_val != null) { //KAPAG NAG NULL UNG MATCH OR SPLITTED VALUES
        //         var is_number = "true";
        //         for (ctr = 0; ctr < splitted_default_val.length; ctr++) {
        //             replace_param1 = splitted_default_val[ctr].trim();
        //             element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');

        //             replace_param2 = element_in_computation.val();
        //             if (element_in_computation.length >= 1) {
        //             } else {
        //                 continue;
        //             }
        //             if (element_in_computation.attr("data-input-type") && element_in_computation.attr("data-input-type") == "Currency") {
        //                 replace_param2 = element_in_computation.val().replace(/,/g, "");
        //             } else {
        //                 replace_param2 = element_in_computation.val();
        //             }
        //             if ($.isNumeric(replace_param2)) {
        //             } else {
        //                 is_number = "false";
        //                 break;
        //             }
        //         }
        //         // console.log("TESTING THIS GREAT FORMULA");
        //         for (ctr = 0; ctr < splitted_default_val.length; ctr++) {
        //             replace_param1 = splitted_default_val[ctr].trim();
        //             if (replace_param1.match(/@Sum\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
        //                 replace_param1 = splitted_default_val[ctr].trim().match(/@Sum\((@[A-Za-z][A-Za-z0-9_]*)\)/);
        //                 replace_param1 = replace_param1[1].replace("@", "");
        //             } else if (replace_param1.match(/@GetMax\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
        //                 replace_param1 = splitted_default_val[ctr].trim().match(/@GetMax\((@[A-Za-z][A-Za-z0-9_]*)\)/);
        //                 replace_param1 = replace_param1[1].replace("@", "");
        //             } else if (replace_param1.match(/@SDev\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
        //                 replace_param1 = splitted_default_val[ctr].trim().match(/@SDev\((@[A-Za-z][A-Za-z0-9_]*)\)/);
        //                 replace_param1 = replace_param1[1].replace("@", "");
        //             } else if (replace_param1.match(/@GetMin\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
        //                 replace_param1 = splitted_default_val[ctr].trim().match(/@GetMin\((@[A-Za-z][A-Za-z0-9_]*)\)/);
        //                 replace_param1 = replace_param1[1].replace("@", "");
        //             } else if (replace_param1.match(/@GetAVG\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
        //                 replace_param1 = splitted_default_val[ctr].trim().match(/@GetAVG\((@[A-Za-z][A-Za-z0-9_]*)\)/);
        //                 replace_param1 = replace_param1[1].replace("@", "");
        //             } else {
        //                 replace_param1 = splitted_default_val[ctr].trim().replace("@", "");
        //             }
        //             if ($(this_self_ele).parents("tr").length >= 1) { // kapag ung may formula ay nasa loob ng row
        //                 if ($(this_self_ele).parents("tr").find('[rep-original-name="' + replace_param1 + '"]').length >= 1) {
        //                     element_in_computation = $(this_self_ele).parents("tr").find('[rep-original-name="' + replace_param1 + '"]');
        //                 } else if ($(this_self_ele).parents("tr").find('[name="' + replace_param1 + '"]').length >= 1) {
        //                     element_in_computation = $(this_self_ele).parents("tr").find('[name="' + replace_param1 + '"]');
        //                 } else {
        //                     element_in_computation = $('[name="' + replace_param1 + '"]');
        //                 }
        //                 /*} else if($("[name='"+replace_param1+"']").parents("tr").length >= 1){// kapag ung fieldname sa formula ay nasa loob ng row
        //                  element_in_computation = $("[name='"+replace_param1+"']").add('[rep-original-name="' + replace_param1 + '"]');*/
        //             } else {
        //                 element_in_computation = $('[name="' + replace_param1 + '"]');
        //                 if (string_default_val.match(/@Sum\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {
        //                     if (string_default_val.match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@", "") == replace_param1 && element_in_computation.length >= 1) {
        //                         if (typeof element_in_computation.attr("event-id-from") != "undefined") {
        //                             if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

        //                             } else {
        //                                 element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
        //                             }
        //                         } else {
        //                             element_in_computation.attr("event-id-from", data_obj_id);
        //                         }
        //                     }
        //                     var second_fn = "@Sum";
        //                 }
        //                 if (string_default_val.match(/@SDev\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {
        //                     if (string_default_val.match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@", "") == replace_param1 && element_in_computation.length >= 1) {
        //                         if (typeof element_in_computation.attr("event-id-from") != "undefined") {
        //                             if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

        //                             } else {
        //                                 element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
        //                             }
        //                         } else {
        //                             element_in_computation.attr("event-id-from", data_obj_id);
        //                         }
        //                     }
        //                     var second_fn = "@SDev";
        //                 }
        //                 if (string_default_val.match(/@GetMax\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {
        //                     if (string_default_val.match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@", "") == replace_param1 && element_in_computation.length >= 1) {
        //                         if (typeof element_in_computation.attr("event-id-from") != "undefined") {
        //                             if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

        //                             } else {
        //                                 element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
        //                             }
        //                         } else {
        //                             element_in_computation.attr("event-id-from", data_obj_id);
        //                         }
        //                     }
        //                     var second_fn = "@GetMax";
        //                 }
        //                 if (string_default_val.match(/@GetMin\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {
        //                     if (string_default_val.match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@", "") == replace_param1 && element_in_computation.length >= 1) {
        //                         if (typeof element_in_computation.attr("event-id-from") != "undefined") {
        //                             if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

        //                             } else {
        //                                 element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
        //                             }
        //                         } else {
        //                             element_in_computation.attr("event-id-from", data_obj_id);
        //                         }
        //                     }
        //                     var second_fn = "@GetMin";
        //                 }
        //                 if (string_default_val.match(/@GetAVG\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {
        //                     if (string_default_val.match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@", "") == replace_param1 && element_in_computation.length >= 1) {
        //                         if (typeof element_in_computation.attr("event-id-from") != "undefined") {
        //                             if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

        //                             } else {
        //                                 element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
        //                             }
        //                         } else {
        //                             element_in_computation.attr("event-id-from", data_obj_id);
        //                         }
        //                     }
        //                     var second_fn = "@GetAVG";
        //                 }
        //             }

        //             // console.log($.trim(replace_param1.split(/@|\(|\)/g).join("")));
        //             // console.log(element_in_computation.attr("name"));

        //             if (replace_param1 == "") {
        //                 continue;
        //             }
        //             if (element_in_computation.length >= 1 && (string_default_val.match(/@GetAVG/) == null && string_default_val.match(/@SDev/) == null && string_default_val.match(/@Sum/) == null && string_default_val.match(/@GetMax/) == null && string_default_val.match(/@GetMin/) == null)) {
        //                 replace_param2 = element_in_computation.val();

        //                 var field_type = "";
        //                 if (typeof element_in_computation.attr("type") !== "undefined") {
        //                     if (element_in_computation.attr("type") == "radio") {
        //                         field_type = "radio";
        //                     }
        //                 }
        //                 if (element_in_computation.attr("data-input-type") && element_in_computation.attr("data-input-type") == "Currency") {
        //                     replace_param2 = element_in_computation.val().replace(/,/g, "");
        //                 } else {
        //                     if (field_type == "radio") {
        //                         replace_param2 = $('[name="' + element_in_computation.attr("name") + '"]:checked').val();
        //                         if (!replace_param2) {
        //                             replace_param2 = "";
        //                         }
        //                     } else {
        //                         replace_param2 = element_in_computation.val();
        //                     }

        //                 }

        //                 this_ini_variant.makeOnChange(element_in_computation, the_field, eventAddressNamespace);
        //                 if (is_number == "false") {//
        //                     if (element_in_computation.attr("data-type") == "float") {
        //                         string_default_val = string_default_val.replace(replace_param1, "Number('" + "" + replace_param2.replace(/\"/g, "\\\"") + "" + "')");
        //                     } else if (element_in_computation.attr("data-type") == "longtext") {
        //                         replace_param2 = replace_param2.replace(/\\/g, "\\\\");
        //                         replace_param2 = replace_param2.replace(/\"/g, "\\\"");
        //                         string_default_val = string_default_val.replace(replace_param1, "\"" + replace_param2 + "\"");
        //                     } else {
        //                         string_default_val = string_default_val.replace(replace_param1, "\"" + replace_param2.replace(/\"/g, "\\\"") + "\"");
        //                     }
        //                 } else {
        //                     string_default_val = string_default_val.replace(replace_param1, replace_param2);
        //                 }
        //             } else if (element_in_computation.length == 0 || (string_default_val.match(/@GetAVG/) != null || string_default_val.match(/@SDev/) != null || string_default_val.match(/@Sum/) != null || string_default_val.match(/@GetMax/) != null || string_default_val.match(/@GetMin/) != null)) {
        //                 var rep_param_w_at = "@" + replace_param1;
        //                 if (typeof second_fn !== "undefined") {
        //                     if (second_fn == "@Sum") {
        //                         rep_param_w_at = "@Sum(" + rep_param_w_at + ")";
        //                     } else if (second_fn == "@GetMax") {
        //                         rep_param_w_at = "@GetMax(" + rep_param_w_at + ")";
        //                     } else if (second_fn == "@SDev") {
        //                         rep_param_w_at = "@SDev(" + rep_param_w_at + ")";
        //                     } else if (second_fn == "@GetMin") {
        //                         rep_param_w_at = "@GetMin(" + rep_param_w_at + ")";
        //                     } else if (second_fn == "@GetAVG") {
        //                         rep_param_w_at = "@GetAVG(" + rep_param_w_at + ")";
        //                     }
        //                 }

        //                 if (rep_param_w_at.indexOf("@Today") >= 0) {

        //                     var this_today = new Date(this_ini_variant.getUpdatedServerTime());

        //                     this_today = this_today.getFullYear() + "-" + StrRight("0" + (this_today.getMonth() + 1), 2) + "-" + StrRight("0" + this_today.getDate(), 2);

        //                     string_default_val = string_default_val.replace(rep_param_w_at, "\"" + this_today + "\"");
        //                 } else if (rep_param_w_at.indexOf("@Now") >= 0) {
        //                     var this_today = new Date(this_ini_variant.getUpdatedServerTime());
        //                     this_today = this_today.getFullYear() + "-" + StrRight("0" + (this_today.getMonth() + 1), 2) + "-" + StrRight("0" + this_today.getDate(), 2) + " " + StrRight("0" + this_today.getHours(), 2) + ":" + StrRight("0" + this_today.getMinutes(), 2) + ":" + StrRight("0" + this_today.getSeconds(), 2);
        //                     string_default_val = string_default_val.replace(rep_param_w_at, "\"" + this_today + "\"");
        //                 } else if (rep_param_w_at.indexOf("@RequestID") >= 0) {
        //                     var getID = $("#ID").val();
        //                     string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getID + "\"");
        //                 } else if (rep_param_w_at.indexOf("@CurrentUser") >= 0) {
        //                     //current_user_ele = $("#frmrequest").find('[name="CurrentUser"]').eq(0)
        //                     var getCurrentUser = "<?php echo $auth['display_name']; ?>";
        //                     string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getCurrentUser + "\"");
        //                 } else if (rep_param_w_at.indexOf("@Requestor") >= 0) {
        //                     //requestor_ele = $("#frmrequest").find('[name="Requestor"]').eq(0)
        //                     // requestor_ele = "<?php echo $auth['display_name']; ?>";
        //                     // $(this_self_ele).find(".getFields_" + data_obj_id).val(requestor_ele);
        //                     var getRequestorVal = "<?php echo $auth['display_name']; ?>";
        //                     string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getRequestorVal + "\"");
        //                 } else if (rep_param_w_at.indexOf("@TrackNo") >= 0) {

        //                     // var self_tn = $(this_self_ele);
        //                     // var gettingValueChangesTrackNo = setInterval(function() {
        //                     //     track_no_ele_val = track_no_ele.val();
        //                     //     if (track_no_ele_val == "") {
        //                     //         self_tn.find(".getFields_" + data_obj_id).val("");
        //                     //     } else {
        //                     //         self_tn.find(".getFields_" + data_obj_id).val(track_no_ele_val);
        //                     //         clearInterval(gettingValueChangesTrackNo);
        //                     //     }
        //                     // }, 100);
        //                     // $(this_self_ele).find(".getFields_" + data_obj_id).val(track_no_ele.val());
        //                     var track_no_ele = $("#frmrequest").find('[name="TrackNo"]').eq(0)
        //                     var getTrackNoVal = track_no_ele.val();
        //                     string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getTrackNoVal + "\"");
        //                 } else if (rep_param_w_at.indexOf("@Status") >= 0) {
        //                     // var self_s = $(this_self_ele);
        //                     // var gettingValueChangesStatus = setInterval(function() {
        //                     //     status_ele_val = status_ele.val();
        //                     //     if (status_ele_val == "") {
        //                     //         self_s.find(".getFields_" + data_obj_id).val("New request");
        //                     //     } else {
        //                     //         self_s.find(".getFields_" + data_obj_id).val(status_ele_val);
        //                     //         clearInterval(gettingValueChangesStatus);
        //                     //     }
        //                     // }, 100);
        //                     var status_ele = $("#frmrequest").find('[name="Status"]').eq(0);
        //                     var getStatusVal = status_ele.val();
        //                     string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getStatusVal + "\"");
        //                 } else if (rep_param_w_at.indexOf("@Department") >= 0) {
        //                     var getDepName = $("[name='Department_Name']").val();
        //                     string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getDepName + "\"");
        //                 } else if (rep_param_w_at.match(/\[[A-Za-z]*\]/) != null) {//FOR SUM AVG ETC FORMULA
        //                     var fieldName = rep_param_w_at.replace(/\[[A-Za-z]*\]|@/g, "");
        //                     var formula_function = rep_param_w_at.match(/\[[A-Za-z]*\]/);
        //                     var get_fields_value = "(";
        //                     if (formula_function[0] == "[sum]") {
        //                         get_fields_value = get_fields_value + "Number('" + $('[name="' + fieldName + '"]').val() + "')";

        //                         this_ini_variant.makeOnChange($('[name="' + fieldName + '"]'), the_field, eventAddressNamespace);
        //                         $('[rep-original-name="' + fieldName + '"]').each(function() {
        //                             //
        //                             get_fields_value = get_fields_value + " + Number('" + $(this).val() + "')";
        //                         });
        //                         get_fields_value = get_fields_value + ")";
        //                         string_default_val = string_default_val.replace(rep_param_w_at, "" + get_fields_value + "");
        //                     }
        //                     if (formula_function[0] == "[Last]") {
        //                         if ($('[rep-original-name="' + fieldName + '"]').length >= 1) {
        //                             var element_in_computation_last = $('[rep-original-name="' + fieldName + '"]').last();
        //                             this_ini_variant.makeOnChange(element_in_computation_last, the_field, eventAddressNamespace);
        //                             if ($.isNumeric(element_in_computation_last.val())) {
        //                                 get_fields_value = get_fields_value + "" + element_in_computation_last.val() + "";
        //                             } else {
        //                                 get_fields_value = get_fields_value + "'" + element_in_computation_last.val() + "'";
        //                             }
        //                             get_fields_value = get_fields_value + ")";
        //                             string_default_val = string_default_val.replace(rep_param_w_at, "" + get_fields_value + "");
        //                         } else if ($('[name="' + fieldName + '"]').length >= 1) {
        //                             var element_in_computation_last = $('[name="' + fieldName + '"]').last();
        //                             this_ini_variant.makeOnChange(element_in_computation_last, the_field, eventAddressNamespace);
        //                             if ($.isNumeric(element_in_computation_last.val())) {
        //                                 get_fields_value = get_fields_value + "" + element_in_computation_last.val() + "";
        //                             } else {
        //                                 get_fields_value = get_fields_value + "'" + element_in_computation_last.val() + "'";
        //                             }
        //                             get_fields_value = get_fields_value + ")";
        //                             string_default_val = string_default_val.replace(rep_param_w_at, "" + get_fields_value + "");
        //                         }
        //                     }
        //                 } else if (rep_param_w_at.match(/@Sum\(@[A-Za-z0-9_]*\)/g) != null) { //FOR @Sum(@Fieldname)
        //                     fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
        //                     var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
        //                     if (fieldExists("\"" + fieldName[1] + "\"") == true) {
        //                         string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
        //                     }
        //                     this_ini_variant.makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
        //                 } else if (rep_param_w_at.match(/@GetMax\(@[A-Za-z0-9_]*\)/g) != null) { //

        //                     fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
        //                     var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
        //                     if (fieldExists("\"" + fieldName[1] + "\"") == true) {
        //                         string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
        //                     }
        //                     this_ini_variant.makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
        //                 } else if (rep_param_w_at.match(/@GetMin\(@[A-Za-z0-9_]*\)/g) != null) { //
        //                     fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
        //                     var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
        //                     if (fieldExists("\"" + fieldName[1] + "\"") == true) {
        //                         string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
        //                     }
        //                     this_ini_variant.makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
        //                 } else if (rep_param_w_at.match(/@SDev\(@[A-Za-z0-9_]*\)/g) != null) { //
        //                     fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
        //                     var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
        //                     if (fieldExists("\"" + fieldName[1] + "\"") == true) {
        //                         string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
        //                     }
        //                     this_ini_variant.makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
        //                 } else if (rep_param_w_at.match(/@GetAVG\(@[A-Za-z0-9_]*\)/g) != null) { //
        //                     fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
        //                     var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
        //                     if (fieldExists("\"" + fieldName[1] + "\"") == true) {
        //                         string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
        //                     }
        //                     this_ini_variant.makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
        //                 }
        //             }

        //         }
        //         console.log("end of testing great formula", string_default_val)
        //         if (string_default_val.indexOf("@") >= 0) {
        //             string_default_val = string_default_val.replace(/@/g, "");
        //         }
        //         if (string_default_val.indexOf(/\'/g) >= 0) {
        //             string_default_val = string_default_val.replace(/\'/g, "\'");
        //         }
        //         if (string_default_val.match(/\"/g) != null) {
        //             string_default_val = string_default_val.replace(/\"/g, "\"");
        //         }
        //         // // console.log(string_default_val)
        //         // if(string_default_val.match(/\\/g) != null){
        //         //  string_default_val = string_default_val.replace(/\\/g,"\\\\");
        //         // }
        //         // // console.log(string_default_val)
        //         // if(string_default_val.match(/\"/g) != null){
        //         //  string_default_val = string_default_val.replace(/\"/g,"\\\"");
        //         // }
        //         // console.log("TESTZZZ")
        //         // console.log(string_default_val)
        //         // alert("WHOA")
        //         if (string_default_val.indexOf("Lookup") >= 0) {

        //         } else {
        //             var eval_parse_status = "";
        //             try {
        //                 eval(String("" + string_default_val));
        //                 eval_parse_status = "ok";
        //                 console.log(this_self_ele, "ok", string_default_val);
        //             } catch (e) {
        //                 eval_parse_status = "not ok";
        //                 console.log(this_self_ele, "not", string_default_val, e);
        //             }
        //             if (eval_parse_status == "ok") {
        //                 if (eval(String(string_default_val)) == "Infinity") {
        //                     $(this_self_ele).find(".getFields_" + data_obj_id).val("Cannot divide by zero");
        //                 } else if (eval(String(string_default_val)) == "Invalid Date") {
        //                     //do not place any value
        //                 } else {
        //                     //THIS IS THE STARTUP VALUE
        //                     $(this_self_ele).find(".getFields_" + data_obj_id).val(eval(String(string_default_val)));
        //                     if ($(this_self_ele).find(".getFields_" + data_obj_id).val() == "NaN") {
        //                         $(this_self_ele).find(".getFields_" + data_obj_id).val("Not a valid computation")
        //                     }
        //                 }
        //             }
        //         }
        //     }
        //     // }
        // },
        "defaultComputed": function(data_obj_id, the_field_ele, this_element, eventAddressNamespace) {
            var fieldname_keywords = [
                "FormID", "WorkflowId", "ID",
                "Requestor", "CurrentUser", "Status",
                "Processor", "LastAction", "DateCreated",
                "DateUpdated", "CreatedBy", "UpdatedBy",
                "Unread", "Node_ID", "Workflow_ID",
                "Mode", "TrackNo", "imported",
                "computedFields", "fieldEnabled", "KeywordsField",
                "Repeater_Data", "Department_Name", "From",
                "To", "Range", "requestorname","Auth"
            ];
            var this_ini_variant = this;
            the_field = the_field_ele;
            this_self_ele = $(this_element);
            var string_default_val = "" + $(this_self_ele).find(".getFields_" + data_obj_id).attr("default-formula-value");

            string_default_val = "" + $(this_self_ele).find(".getFields_" + data_obj_id).attr("default-formula-value");

            if (string_default_val.indexOf("@Lookup") >= 0) {
                return;
            }
            if (string_default_val.indexOf("@RecordCount") >= 0) {
                return;
            }
            if (string_default_val.indexOf("@LookupWhere") >= 0) {
			console.log("HERE TRACK",the_field,this_self_ele)
                return;
            }
            if (string_default_val.indexOf("@LookupSDev") >= 0) {
                return;
            }
            if (string_default_val.indexOf("@LookupAVG") >= 0) {
                return;
            }
            if (string_default_val.indexOf("@LookupAuthInfo") >= 0) {
                return;
            }
            if (string_default_val.indexOf(/^@Total\(*.\)$/) >= 0) {
                return;
            }

            splitted_default_val = string_default_val.match(/@GetAVG\(@[A-Za-z0-9_]*\)|@SDev\(@[A-Za-z0-9_]*\)|@GetMin\(@[A-Za-z0-9_]*\)|@GetMax\(@[A-Za-z0-9_]*\)|@Sum\(@[A-Za-z0-9_]*\)|@(\[[a-zA-Z0-9_\'\"]*\]){3}|@[A-Za-z0-9_]*/g);
            console.log("HEY",splitted_default_val)

            if (splitted_default_val != null) { //KAPAG NAG NULL UNG MATCH OR SPLITTED VALUES
                var is_number = "true";
                for (ctr = 0; ctr < splitted_default_val.length; ctr++) {
                    replace_param1 = splitted_default_val[ctr].trim();
                    element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');

                    replace_param2 = element_in_computation.val();
                    if (element_in_computation.length >= 1) {
                    } else {
                        continue;
                    }
                    if ($.isNumeric(replace_param2)) {
                    } else {
                        is_number = "false";
                        break;
                    }
                }
                // console.log("TESTING THIS GREAT FORMULA");
                for (ctr = 0; ctr < splitted_default_val.length; ctr++) {

                    replace_param1 = splitted_default_val[ctr].trim();
                    if (replace_param1.match(/@Sum\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
                        replace_param1 = splitted_default_val[ctr].trim().match(/@Sum\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                        replace_param1 = replace_param1[1].replace("@", "");
                    } else if (replace_param1.match(/@GetMax\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
                        replace_param1 = splitted_default_val[ctr].trim().match(/@GetMax\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                        replace_param1 = replace_param1[1].replace("@", "");
                    } else if (replace_param1.match(/@SDev\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
                        replace_param1 = splitted_default_val[ctr].trim().match(/@SDev\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                        replace_param1 = replace_param1[1].replace("@", "");
                    } else if (replace_param1.match(/@GetMin\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
                        replace_param1 = splitted_default_val[ctr].trim().match(/@GetMin\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                        replace_param1 = replace_param1[1].replace("@", "");
                    } else if (replace_param1.match(/@GetAVG\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
                        replace_param1 = splitted_default_val[ctr].trim().match(/@GetAVG\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                        replace_param1 = replace_param1[1].replace("@", "");
                    } else {
                        replace_param1 = splitted_default_val[ctr].trim().replace("@", "");
                    }
                    if ($(this_self_ele).parents("tr").length >= 1) { // kapag ung may formula ay nasa loob ng row
                        if ($(this_self_ele).parents("tr").find('[rep-original-name="' + replace_param1 + '"]').length >= 1) {
                            element_in_computation = $(this_self_ele).parents("tr").find('[rep-original-name="' + replace_param1 + '"]');
                        } else if ($(this_self_ele).parents("tr").find('[name="' + replace_param1 + '"]').length >= 1) {
                            element_in_computation = $(this_self_ele).parents("tr").find('[name="' + replace_param1 + '"]');
                        } else {
                            element_in_computation = $('[name="' + replace_param1 + '"]');
                        }
                        /*} else if($("[name='"+replace_param1+"']").parents("tr").length >= 1){// kapag ung fieldname sa formula ay nasa loob ng row
                         element_in_computation = $("[name='"+replace_param1+"']").add('[rep-original-name="' + replace_param1 + '"]');*/
                    } else {
                        element_in_computation = $('[name="' + replace_param1 + '"]');
                        if (splitted_default_val[ctr].trim().match(/@Sum\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {
                            if (splitted_default_val[ctr].trim().match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@", "") == replace_param1 && element_in_computation.length >= 1) {
                                if (typeof element_in_computation.attr("event-id-from") != "undefined") {
                                    if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

                                    } else {
                                        element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
                                    }
                                } else {
                                    element_in_computation.attr("event-id-from", data_obj_id);
                                }
                            }
                            var second_fn = "@Sum";
                        }
                        if (splitted_default_val[ctr].trim().match(/@SDev\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {
                            if (splitted_default_val[ctr].trim().match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@", "") == replace_param1 && element_in_computation.length >= 1) {
                                if (typeof element_in_computation.attr("event-id-from") != "undefined") {
                                    if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

                                    } else {
                                        element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
                                    }
                                } else {
                                    element_in_computation.attr("event-id-from", data_obj_id);
                                }
                            }
                            var second_fn = "@SDev";
                        }
                        if (splitted_default_val[ctr].trim().match(/@GetMax\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {
                            if (splitted_default_val[ctr].trim().match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@", "") == replace_param1 && element_in_computation.length >= 1) {
                                if (typeof element_in_computation.attr("event-id-from") != "undefined") {
                                    if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

                                    } else {
                                        element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
                                    }
                                } else {
                                    element_in_computation.attr("event-id-from", data_obj_id);
                                }
                            }
                            var second_fn = "@GetMax";
                        }
                        if (splitted_default_val[ctr].trim().match(/@GetMin\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {
                            if (splitted_default_val[ctr].trim().match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@", "") == replace_param1 && element_in_computation.length >= 1) {
                                if (typeof element_in_computation.attr("event-id-from") != "undefined") {
                                    if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

                                    } else {
                                        element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
                                    }
                                } else {
                                    element_in_computation.attr("event-id-from", data_obj_id);
                                }
                            }
                            var second_fn = "@GetMin";
                        }
                        if (splitted_default_val[ctr].trim().match(/@GetAVG\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {
                            if (splitted_default_val[ctr].trim().match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@", "") == replace_param1 && element_in_computation.length >= 1) {
                                if (typeof element_in_computation.attr("event-id-from") != "undefined") {
                                    if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

                                    } else {
                                        element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
                                    }
                                } else {
                                    element_in_computation.attr("event-id-from", data_obj_id);
                                }
                            }
                            var second_fn = "@GetAVG";
                        }
                    }

                    // console.log($.trim(replace_param1.split(/@|\(|\)/g).join("")));
                    // console.log(element_in_computation.attr("name"));

                    if (replace_param1 == "") {
                        continue;
                    }
                    // alert(splitted_default_val[ctr].replace("@","")+"TESTTT"+splitted_default_val[ctr].indexOf(fieldname_keywords))
                    if (element_in_computation.length >= 1 && fieldname_keywords.indexOf(splitted_default_val[ctr].replace("@", "")) <= -1 && (splitted_default_val[ctr].trim().match(/@GetAVG/) == null && splitted_default_val[ctr].trim().match(/@SDev/) == null && splitted_default_val[ctr].trim().match(/@Sum/) == null && splitted_default_val[ctr].trim().match(/@GetMax/) == null && splitted_default_val[ctr].trim().match(/@GetMin/) == null)) {
                        
                        replace_param2 = element_in_computation.val();
                        // console.log("DC");
                        // console.log(element_in_computation);
                        try {
                            //if(element_in_computation.parents("tr").length >= 1){
                            //  if(the_field.attr("default-formula-value")){
                            //      if(the_field.attr("default-type")){
                            //          if(the_field.attr("default-type") == "computed"){
                            //              if(the_field.attr("default-formula-value").indexOf("@Sum") >= 0 ){
                            //                  element_in_computation = $(element_in_computation.selector+", [rep-original-name='"+$.trim(replace_param1.split(/@|\(|\)/g).join(""))+"']")
                            //                  element_in_computation.each(function(eqi){
                            //                      $(this).attr("event-id-from", the_field.parents(".setOBJ").eq(0).attr("data-object-id"));
                            //                  })
                            //              }
                            //          }
                            //      }
                            //  }
                            //}
                        } catch (errr) {
                        }
                        //if(this_self_ele.attr("name")=="TotalRunBal"){
                        //  console.log("ARRGH2   "+$.trim(replace_param1.split(/@|\(|\)/g).join("")))
                        //  console.log(this_self_ele.attr("default-formula-value"))
                        //  console.log(this_self_ele)
                        //  console.log(this_self_ele.attr("name"))
                        //  console.log(element_in_computation)
                        //  console.log("ARRGH2----")
                        //}
                        //console.log("PALA"+string_default_val)
                        //console.log("MAKEONCHANGE",element_in_computation,this_self_ele)
                        this_ini_variant.makeOnChange(element_in_computation, the_field, eventAddressNamespace);
                        if (is_number == "false") {//
                            if (element_in_computation.attr("data-type") == "float" || element_in_computation.attr("data-type") == "double") {
                                string_default_val = string_default_val.replace(replace_param1, "Number('" + "" + replace_param2.replace(/\"/g, "\\\"").replace(",", "") + "" + "')");
                            } else if (element_in_computation.attr("data-type") == "longtext") {
                                replace_param2 = replace_param2.replace(/\\/g, "\\\\");
                                replace_param2 = replace_param2.replace(/\"/g, "\\\"");
                                string_default_val = string_default_val.replace(replace_param1, "\"" + replace_param2 + "\"");
                            } else {
                                string_default_val = string_default_val.replace(replace_param1, "\"" + replace_param2.replace(/\"/g, "\\\"") + "\"");
                            }
                        } else {
                            string_default_val = string_default_val.replace(replace_param1, replace_param2);
                        }
                    } else if ((element_in_computation.length == 0 || fieldname_keywords.indexOf(splitted_default_val[ctr].replace("@", "")) >= 0) || (string_default_val.match(/@GetAVG/) != null || string_default_val.match(/@SDev/) != null || string_default_val.match(/@Sum/) != null || string_default_val.match(/@GetMax/) != null || string_default_val.match(/@GetMin/) != null)) {
                        var rep_param_w_at = "@" + replace_param1;

                        if (typeof second_fn !== "undefined") {
                            if (second_fn == "@Sum") {
                                rep_param_w_at = "@Sum(" + rep_param_w_at + ")";
                            } else if (second_fn == "@GetMax") {
                                rep_param_w_at = "@GetMax(" + rep_param_w_at + ")";
                            } else if (second_fn == "@SDev") {
                                rep_param_w_at = "@SDev(" + rep_param_w_at + ")";
                            } else if (second_fn == "@GetMin") {
                                rep_param_w_at = "@GetMin(" + rep_param_w_at + ")";
                            } else if (second_fn == "@GetAVG") {
                                rep_param_w_at = "@GetAVG(" + rep_param_w_at + ")";
                            }
                        }

                        if (rep_param_w_at.indexOf("@Today") >= 0) {

                            var this_today = new Date(this_ini_variant.getUpdatedServerTime());
                            this_today = this_today.getFullYear() + "-" + StrRight("0" + (this_today.getMonth() + 1), 2) + "-" + StrRight("0" + this_today.getDate(), 2);

                            string_default_val = string_default_val.replace(rep_param_w_at, "\"" + this_today + "\"");
                        } else if (rep_param_w_at.indexOf("@Now") >= 0) {
                            var this_today = new Date(this_ini_variant.getUpdatedServerTime());
                            this_today = this_today.getFullYear() + "-" + StrRight("0" + (this_today.getMonth() + 1), 2) + "-" + StrRight("0" + this_today.getDate(), 2) + " " + StrRight("0" + this_today.getHours(), 2) + ":" + StrRight("0" + this_today.getMinutes(), 2) + ":" + StrRight("0" + this_today.getSeconds(), 2);
                            string_default_val = string_default_val.replace(rep_param_w_at, "\"" + this_today + "\"");
                        } else if (rep_param_w_at.indexOf("@RequestID") >= 0) {
                            var getID = $("#ID").val();
                            string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getID + "\"");
                        } else if (rep_param_w_at.indexOf("@CurrentUser") >= 0) {
                            var current_user_ele = $("#frmrequest").find('[name="CurrentUser"]').eq(0);
                            var current_user_name = current_user_ele.attr("current-user-name");
                            // var getCurrentUser = "<?php echo $auth['display_name']; ?>";
                            // string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getCurrentUser + "\"");
                            string_default_val = string_default_val.replace(rep_param_w_at, "\"" + current_user_name + "\"");
                        } else if (rep_param_w_at.indexOf("@Processor") >= 0) {

                            if ($("[name='ID']").val() == "0") {
                                var processor_user_ele = $('[name="Processor"]');
                                var processor_name = processor_user_ele.attr("processor-name");
                            } else {
                                var processor_user_ele = $("#processor_display");
                                var processor_name = processor_user_ele.text();
                            }

                            // var getCurrentUser = "<?php echo $auth['display_name']; ?>";
                            // string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getCurrentUser + "\"");
                            string_default_val = string_default_val.replace(rep_param_w_at, "\"" + processor_name + "\"");
                        } else if (rep_param_w_at.indexOf("@Requestor") >= 0) {
                            // requestor_ele = "<?php echo $auth['display_name']; ?>";
                            // $(this_self_ele).find(".getFields_" + data_obj_id).val(requestor_ele);
                            // var getRequestorVal = "<?php echo $auth['display_name']; ?>";
                            if ($("[name='ID']").val() == "0") {
                                var requestor_ele = $("#frmrequest").find('[name="Requestor"]').eq(0);
                                var requestor_name = requestor_ele.attr("requestor-name");
                            } else {
                                var requestor_ele = $("#requestor_display");
                                var requestor_name = requestor_ele.text();
                            }

                            // string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getRequestorVal + "\"");
                            string_default_val = string_default_val.replace(rep_param_w_at, "\"" + requestor_name + "\"");
                        } else if (rep_param_w_at.indexOf("@TrackNo") >= 0) {


                            // var self_tn = $(this_self_ele);
                            // var gettingValueChangesTrackNo = setInterval(function() {
                            //     track_no_ele_val = track_no_ele.val();
                            //     if (track_no_ele_val == "") {
                            //         self_tn.find(".getFields_" + data_obj_id).val("");
                            //     } else {
                            //         self_tn.find(".getFields_" + data_obj_id).val(track_no_ele_val);
                            //         clearInterval(gettingValueChangesTrackNo);
                            //     }
                            // }, 100);
                            // $(this_self_ele).find(".getFields_" + data_obj_id).val(track_no_ele.val());
                            var track_no_ele = $("#frmrequest").find('[name="TrackNo"]').eq(0)
                            var getTrackNoVal = track_no_ele.val();
                            string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getTrackNoVal + "\"");
                        } else if (rep_param_w_at.indexOf("@Status") >= 0) {
                            // var self_s = $(this_self_ele);
                            // var gettingValueChangesStatus = setInterval(function() {
                            //     status_ele_val = status_ele.val();
                            //     if (status_ele_val == "") {
                            //         self_s.find(".getFields_" + data_obj_id).val("New request");
                            //     } else {
                            //         self_s.find(".getFields_" + data_obj_id).val(status_ele_val);
                            //         clearInterval(gettingValueChangesStatus);
                            //     }
                            // }, 100);
                            var status_ele = $("#frmrequest").find('[name="Status"]').eq(0);
                            var getStatusVal = status_ele.val();
                            string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getStatusVal + "\"");
                        } else if (rep_param_w_at.indexOf("@Department") >= 0) {
                            var getDepName = $("[name='Department_Name']").val();
                            string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getDepName + "\"");

                        // } else if (rep_param_w_at.match(/\[[A-Za-z]*\]/) != null) {//FOR SUM AVG ETC FORMULA
                        //     alert("QUARANTINe")
                        //     var fieldName = rep_param_w_at.replace(/\[[A-Za-z]*\]|@/g, "");
                        //     var formula_function = rep_param_w_at.match(/\[[A-Za-z]*\]/);
                        //     var get_fields_value = "(";
                        //     if (formula_function[0] == "[sum]") {
                        //         get_fields_value = get_fields_value + "Number('" + $('[name="' + fieldName + '"]').val() + "')";

                        //         this_ini_variant.makeOnChange($('[name="' + fieldName + '"]'), the_field, eventAddressNamespace);
                        //         $('[rep-original-name="' + fieldName + '"]').each(function() {
                        //             //
                        //             get_fields_value = get_fields_value + " + Number('" + $(this).val() + "')";
                        //         });
                        //         get_fields_value = get_fields_value + ")";
                        //         string_default_val = string_default_val.replace(rep_param_w_at, "" + get_fields_value + "");
                        //     }
                        //     if (formula_function[0] == "[Last]") {
                        //         if ($('[rep-original-name="' + fieldName + '"]').length >= 1) {
                        //             var element_in_computation_last = $('[rep-original-name="' + fieldName + '"]').last();
                        //             this_ini_variant.makeOnChange(element_in_computation_last, the_field, eventAddressNamespace);
                        //             if ($.isNumeric(element_in_computation_last.val())) {
                        //                 get_fields_value = get_fields_value + "" + element_in_computation_last.val() + "";
                        //             } else {
                        //                 get_fields_value = get_fields_value + "'" + element_in_computation_last.val() + "'";
                        //             }
                        //             get_fields_value = get_fields_value + ")";
                        //             string_default_val = string_default_val.replace(rep_param_w_at, "" + get_fields_value + "");
                        //         } else if ($('[name="' + fieldName + '"]').length >= 1) {
                        //             var element_in_computation_last = $('[name="' + fieldName + '"]').last();
                        //             this_ini_variant.makeOnChange(element_in_computation_last, the_field, eventAddressNamespace);
                        //             if ($.isNumeric(element_in_computation_last.val())) {
                        //                 get_fields_value = get_fields_value + "" + element_in_computation_last.val() + "";
                        //             } else {
                        //                 get_fields_value = get_fields_value + "'" + element_in_computation_last.val() + "'";
                        //             }
                        //             get_fields_value = get_fields_value + ")";
                        //             string_default_val = string_default_val.replace(rep_param_w_at, "" + get_fields_value + "");
                        //         }
                        //     }
                        } else if (rep_param_w_at.match(/@Sum\(@[A-Za-z0-9_]*\)/g) != null) { //FOR @Sum(@Fieldname)
                            fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
                            var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
                            if (fieldExists("\"" + fieldName[1] + "\"") == true) {
                                string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                            }
                            this_ini_variant.makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
                        } else if (rep_param_w_at.match(/@GetMax\(@[A-Za-z0-9_]*\)/g) != null) { //

                            fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
                            var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
                            if (fieldExists("\"" + fieldName[1] + "\"") == true) {
                                string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                            }
                            this_ini_variant.makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
                        } else if (rep_param_w_at.match(/@GetMin\(@[A-Za-z0-9_]*\)/g) != null) { //
                            fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
                            var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
                            if (fieldExists("\"" + fieldName[1] + "\"") == true) {
                                string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                            }
                            this_ini_variant.makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
                        } else if (rep_param_w_at.match(/@SDev\(@[A-Za-z0-9_]*\)/g) != null) { //
                            fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
                            var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
                            if (fieldExists("\"" + fieldName[1] + "\"") == true) {
                                string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                            }
                            this_ini_variant.makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
                        } else if (rep_param_w_at.match(/@GetAVG\(@[A-Za-z0-9_]*\)/g) != null) { //
                            fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
                            var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
                            if (fieldExists("\"" + fieldName[1] + "\"") == true) {
                                string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                            }
                            this_ini_variant.makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
                        } else if (splitted_default_val[ctr].match(/@(\[[a-zA-Z0-9_\'\"]*\]){3}/g) != null){
                            var reg_exp = new RegExp("\\[[@a-zA-Z0-9_\\\'\\\"]*\\](?!\\s)", 'g');
                            var value_get = "";
                            if(splitted_default_val[ctr].match(reg_exp) != null){
                                var match_res = splitted_default_val[ctr].match(reg_exp).filter(Boolean);
                                var tbl_name = match_res[0].replace(/\[|\]/g,"");
                                var field_name = match_res[1].replace(/\[|\]/g,"");
                                var fn_index = match_res[2].replace(/\[|\]/g,"");
                                if($.isNumeric(fn_index)){
                                    var collect_fn_ele = $('[table-name="'+tbl_name+'"]').find('[name="'+field_name+'"]');
                                    collect_fn_ele = collect_fn_ele.add($('[table-name="'+tbl_name+'"]').find('[rep-original-name="'+field_name+'"]'));
                                    if(collect_fn_ele.eq(fn_index).attr("data-type") == "float" || collect_fn_ele.eq(fn_index).attr("data-type") == "double"){
                                        value_get = "Number("+collect_fn_ele.eq(fn_index).val()+")";
                                    }else{
                                        value_get = "\'"+collect_fn_ele.eq(fn_index).val()+"\'";
                                    }

                                    if(collect_fn_ele.eq(0).attr("event-id-from")){
                                        var eids = collect_fn_ele.eq(0).attr("event-id-from").split(",");
                                        if(eids.indexOf(""+data_obj_id) < 0){
                                            collect_fn_ele.eq(0).attr("event-id-from",collect_fn_ele.eq(0).attr("event-id-from")+","+data_obj_id)
                                        }
                                    }else{
                                        collect_fn_ele.eq(0).attr("event-id-from",data_obj_id)
                                    }
                                    
                                    this_ini_variant.makeOnChange(collect_fn_ele.eq(fn_index), the_field, eventAddressNamespace);
                                }else if(fn_index == "RootRowIndex"){
                                    fn_index = GetRowIndex(this_self_ele);

                                    var collect_fn_ele = $('[table-name="'+tbl_name+'"]').find('[name="'+field_name+'"]');
                                    collect_fn_ele = collect_fn_ele.add($('[table-name="'+tbl_name+'"]').find('[rep-original-name="'+field_name+'"]'));
                                    if(collect_fn_ele.eq(fn_index).attr("data-type") == "float" || collect_fn_ele.eq(fn_index).attr("data-type") == "double"){
                                        value_get = "Number("+collect_fn_ele.eq(fn_index).val()+")";
                                    }else{
                                        value_get = "\'"+collect_fn_ele.eq(fn_index).val()+"\'";
                                    }

                                    if(collect_fn_ele.eq(0).attr("event-id-from")){
                                        var eids = collect_fn_ele.eq(0).attr("event-id-from").split(",");
                                        if(eids.indexOf(""+data_obj_id) < 0){
                                            collect_fn_ele.eq(0).attr("event-id-from",collect_fn_ele.eq(0).attr("event-id-from")+","+data_obj_id)
                                        }
                                    }else{
                                        collect_fn_ele.eq(0).attr("event-id-from",data_obj_id)
                                    }
                                    this_ini_variant.makeOnChange(collect_fn_ele.eq(fn_index), the_field, eventAddressNamespace);
                                }else if(fn_index == "RowIndex"){
                                    // fn_index = GetRowIndex($('[table-name="'+tbl_name+'"]').find('[name="'+field_name+'"]'));

                                    // var collect_fn_ele = $('[table-name="'+tbl_name+'"]').find('[name="'+field_name+'"]');
                                    // collect_fn_ele = collect_fn_ele.add($('[table-name="'+tbl_name+'"]').find('[rep-original-name="'+field_name+'"]'));
                                    // if(collect_fn_ele.eq(fn_index).attr("data-type") == "float"){
                                    //     value_get = "Number("+collect_fn_ele.eq(fn_index).val()+")";
                                    // }else{
                                    //     value_get = "\'"+collect_fn_ele.eq(fn_index).val()+"\'";
                                    // }

                                    // if(collect_fn_ele.eq(0).attr("event-id-from")){
                                    //     var eids = collect_fn_ele.eq(0).attr("event-id-from").split(",");
                                    //     if(eids.indexOf(""+data_obj_id) < 0){
                                    //         collect_fn_ele.eq(0).attr("event-id-from",collect_fn_ele.eq(0).attr("event-id-from")+","+data_obj_id)
                                    //     }
                                    // }else{
                                    //     collect_fn_ele.eq(0).attr("event-id-from",data_obj_id)
                                    // }
                                    
                                    // this_ini_variant.makeOnChange(collect_fn_ele.eq(fn_index), the_field, eventAddressNamespace);
                                }
                                
                            }
                            var reg_exp_repl = new RegExp(splitted_default_val[ctr].replace(/\[/g,"\\\[").replace(/\]/g,"\\\]").replace(/\'/g,"\\\'").replace(/\"/g,"\\\""),"g");
                            string_default_val = string_default_val.replace(reg_exp_repl, value_get);

                        }
                    }

                }
                //console.log("end of testing great formula",string_default_val)
                if (string_default_val.indexOf("@") >= 0) {
                    string_default_val = string_default_val.replace(/@/g, "");
                }
                if (string_default_val.indexOf(/\'/g) >= 0) {
                    string_default_val = string_default_val.replace(/\'/g, "\'");
                }
                if (string_default_val.match(/\"/g) != null) {
                    string_default_val = string_default_val.replace(/\"/g, "\"");
                }
                if (string_default_val.match(/\n/g) != null) {
                    //string_default_val = string_default_val.replace(/\n/g, "\\n"); 
                }
                // // console.log(string_default_val)
                // if(string_default_val.match(/\\/g) != null){
                //  string_default_val = string_default_val.replace(/\\/g,"\\\\");
                // }
                // // console.log(string_default_val)
                // if(string_default_val.match(/\"/g) != null){
                //  string_default_val = string_default_val.replace(/\"/g,"\\\"");
                // }
                // console.log("TESTZZZ")
                // console.log(string_default_val)
                // alert("WHOA")
                if (string_default_val.indexOf("Lookup") >= 0) {

                } else {
                    var eval_parse_status = "";
                    try {
                        eval(String("" + string_default_val));
                        eval_parse_status = "ok";
                        console.log(this_self_ele, "ok",string_default_val);
                    } catch (e) {
                        eval_parse_status = "not ok";
                        console.log(this_self_ele,"not",string_default_val,e);
                    }
                    if (eval_parse_status == "ok") {
                        if (eval(String(string_default_val)) == "Infinity") {
                            $(this_self_ele).find(".getFields_" + data_obj_id).val("Cannot divide by zero");
                        } else if (eval(String(string_default_val)) == "Invalid Date") {
                            //do not place any value
                        } else {
                            //THIS IS THE STARTUP VALUE
                            $(this_self_ele).find(".getFields_" + data_obj_id).val(eval(String(string_default_val)));
                            if ($(this_self_ele).find(".getFields_" + data_obj_id).val() == "NaN") {
                                $(this_self_ele).find(".getFields_" + data_obj_id).val("Not a valid computation")
                            }
                        }
                    }
                }
            }
            // }
        },
        "commitChangesDefaultVal": function (){
            var form_ele = $('.preview_content').find('#frmrequest').eq(0).find('.loaded_form_content').eq(0);
            var skip_ele_field = ['labelOnly','tab-panel','table','createLine','imageOnly'];
            form_ele.find('.setOBJ').each(function(){
                var dis_self = $(this);
                var doid = dis_self.attr('data-object-id');
                var setOBJ_data_type = dis_self.attr('data-type');
                if(skip_ele_field.indexOf(setOBJ_data_type) < 0){
                    dis_self.find('.getFields_'+doid).trigger('change');
                }
            });
        },
        "setDefaultValues": function() {
            var this_ini_variant = this;
            var form_json_data = $("body").data()["user_form_json_data"];
            if (typeof form_json_data != "undefined" && form_json_data != '') {

                if ($(".setOBJ").length >= 1) {
                    //fields having a defaultfields
                    //set static values
                    $(".setOBJ").each(function(eqi_setOBJ) {
                        var data_obj_id = $(this).attr("data-object-id");
                        var the_field = $(this).find(".getFields_" + data_obj_id);
                        if (the_field.attr("default-type")) {
                            if (the_field.attr("default-type") == "static") {
                                if (typeof the_field.attr("default-static-value") != "undefined") {
                                    if (the_field.attr("default-static-value").length >= 1) {
                                        the_field.val(the_field.attr("default-static-value"));
                                    }
                                }
                            } else if (the_field.attr("default-type") == "computed") {

                            }
                        }
                    });
                    //set default values
                    $(".setOBJ").each(function(eqi_setOBJ) {
                        var data_obj_id = $(this).attr("data-object-id");
                        //try{
                        if (typeof form_json_data.form_json["" + data_obj_id] != "undefined") {
                            var the_field = $(this).find(".getFields_" + data_obj_id);
                            if (
                                    the_field.attr("type") && (
                                    the_field.attr("type") == "radio" ||
                                    the_field.attr("type") == "checkbox"
                                    )
                                    ) {
                                if (typeof form_json_data.form_json["" + data_obj_id].defaultValues != "undefined") {
                                    $.each(form_json_data.form_json["" + data_obj_id].defaultValues, function(index, item) {
                                        var radio_check_strvalue = form_json_data.form_json["" + data_obj_id].defaultValues[index];
                                        if ($(the_field).eq(index).length >= 1 && $(the_field).eq(index).val() == radio_check_strvalue) {
                                            if ($("#getID").val() == "0") {
                                                $(the_field).eq(index).prop("checked", true);
                                            }
                                        }
                                    });
                                }
                            } else if (the_field.prop("tagName") == "SELECT") {
                                if (typeof form_json_data.form_json["" + data_obj_id].defaultValues != "undefined") {
                                    $.each(form_json_data.form_json["" + data_obj_id].defaultValues, function(index, item) {
                                        var select_strval = form_json_data.form_json["" + data_obj_id].defaultValues[index];
                                        if ($(the_field).children("option").eq(index).length >= 1 && $(the_field).children("option").eq(index).val() == select_strval) {
                                            $(the_field).children("option").eq(index).prop("selected", true);
                                        }
                                    });
                                }
                            } else {
                                if ($(this).find(".getFields_" + data_obj_id).attr("default-type")) {
                                    if ($(this).find(".getFields_" + data_obj_id).attr("default-type") == "static") {
                                        if (typeof $(this).find(".getFields_" + data_obj_id).attr("default-static-value") != "undefined") {
                                            if ($(this).find(".getFields_" + data_obj_id).attr("default-static-value").length >= 1) {
                                                // console.log($(this).find(".getFields_" + data_obj_id).attr("name"))
                                                $(this).find(".getFields_" + data_obj_id).val($(this).find(".getFields_" + data_obj_id).attr("default-static-value"));
                                            }
                                        }
                                    } else if ($(this).find(".getFields_" + data_obj_id).attr("default-type") == "computed") {
                                        this_ini_variant.defaultComputed(data_obj_id, the_field, this, "startUpDefaultValComputed");
                                    }
                                }
                            }
                        }
                        // }catch(error){
                        //    console.log("ERROR on getting the json datas of this individual field");
                        //    console.log("OR the json variable form_json_data.form_json[''+"+data_obj_id+"] is not existing this id:->["+data_obj_id+"]");
                        //    console.log("OR the values of computed is not well defined");
                        //    console.log(error)
                        // }
                        // console.log($('[name="Date_Hired"]').val())
                        // console.log($(this).find(".getFields_" + data_obj_id).attr("name"))
                        // console.log($(this).find(".getFields_" + data_obj_id).attr("default-computed-value"))
                    });
                    // $('[default-type="computed"][default-formula-value]').change();

                }
                $('[default-type="static"]').change();
            } else {
                console.log("form_json_data is undefined");
            }
        },
        // "makeOnChange": function(fieldAffected, fieldWithComputationParam, eventAddressNamespace) {
        //     var this_ini_variant = this;
        //     var fieldWithComputation = $(fieldWithComputationParam);
        //     var this_ini_variant = this;
        //     // console.log("check affected")
        //     // console.log(fieldAffected)
        //     if (fieldWithComputation.attr("default-formula-value")) {
        //         // if(fieldWithComputation.attr("default-formula-value").indexOf("Lookup") >= 0){
        //         // populateFormula();

        //         // }else{
        //         var event_string = "keyup change";
        //         if (typeof eventAddressNamespace == "undefined") {
        //             //do nothing

        //         } else {
        //             event_string = "keyup." + eventAddressNamespace + " change." + eventAddressNamespace;//namespace added for destroying repeated events
        //         }
        //         // console.log(event_string)
        //         // console.log("eto na ba un")
        //         // console.log(fieldAffected)
        //         if ($(fieldAffected).attr("event-id-from")) {
        //             var ids_event_from = $(fieldAffected).attr("event-id-from");
        //             var array_ids_event_from = ids_event_from.split(",");
        //             if (array_ids_event_from.indexOf(fieldWithComputation.closest(".setOBJ").attr("data-object-id")) >= 0) {

        //             } else {
        //                 $(fieldAffected).attr("event-id-from", $(fieldAffected).attr("event-id-from") + "," + fieldWithComputation.closest(".setOBJ").attr("data-object-id"));
        //             }
        //         } else {
        //             //console.log($(fieldAffected).attr("event-id-from", "" + fieldWithComputation.closest(".setOBJ").attr("data-object-id")));
        //         }
        //         // console.log("HAYS")
        //         // console.log(fieldWithComputation)

        //         $(fieldAffected).on(event_string, {"fieldWithComputation": fieldWithComputation}, function(e) {
        //             // e.stopPropagation();//AYAW GUMANA :<<<
        //             // event.stopPropagation();//AYAW GUMANA :<<<
        //             var fieldWithComputation = e.data.fieldWithComputation;
        //             // try{
        //             // console.log("ETO NGA BA UN?")
        //             // console.log(fieldWithComputation)
        //             var string_default_val = "" + fieldWithComputation.attr("default-formula-value");
        //             // console.log("eto ung formula")
        //             // console.log(string_default_val)
        //             // console.log(fieldWithComputation)
        //             if (string_default_val.indexOf("@Lookup") >= 0) {
        //                 return;
        //             }
        //             if (string_default_val.indexOf("@LookupWhere") >= 0) {
        //                 return;
        //             }
        //             if (string_default_val.indexOf("@LookupGetMin") >= 0) {
        //                 return;
        //             }
        //             if (string_default_val.indexOf("@LookupGetMax") >= 0) {
        //                 return;
        //             }
        //             if (string_default_val.indexOf("@LookupSDev") >= 0) {
        //                 return;
        //             }
        //             if (string_default_val.indexOf("@LookupAVG") >= 0) {
        //                 return;
        //             }
        //             if (string_default_val.indexOf(/^@Total\(*.\)$/) >= 0) {
        //                 return;
        //             }
        //             var string_field_formula = string_default_val;
        //             try {
        //                 splitted_default_val = string_default_val.match(/@GetAVG\(@[A-Za-z0-9_]*\)|@SDev\(@[A-Za-z0-9_]*\)|@GetMin\(@[A-Za-z0-9_]*\)|@GetMax\(@[A-Za-z0-9_]*\)|@Sum\(@[A-Za-z0-9_]*\)|@[a-zA-Z0-9_]*\[[A-Za-z]*\]|@[a-zA-Z0-9_]*/g);
        //             } catch (error) {
        //                 //console.log("the formula value is not defined");
        //             }
        //             var is_number = "true";
        //             for (ctr = 0; ctr < splitted_default_val.length; ctr++) {
        //                 replace_param1 = splitted_default_val[ctr].trim();
        //                 if (replace_param1.match(/@Sum\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
        //                     replace_param1 = splitted_default_val[ctr].trim().match(/@Sum\((@[A-Za-z][A-Za-z0-9_]*)\)/);
        //                     replace_param1 = replace_param1[1].replace("@", "");
        //                 } else if (replace_param1.match(/@GetMax\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
        //                     replace_param1 = splitted_default_val[ctr].trim().match(/@GetMax\((@[A-Za-z][A-Za-z0-9_]*)\)/);
        //                     replace_param1 = replace_param1[1].replace("@", "");
        //                 } else if (replace_param1.match(/@GetMin\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
        //                     replace_param1 = splitted_default_val[ctr].trim().match(/@GetMin\((@[A-Za-z][A-Za-z0-9_]*)\)/);
        //                     replace_param1 = replace_param1[1].replace("@", "");
        //                 } else if (replace_param1.match(/@SDev\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
        //                     replace_param1 = splitted_default_val[ctr].trim().match(/@SDev\((@[A-Za-z][A-Za-z0-9_]*)\)/);
        //                     replace_param1 = replace_param1[1].replace("@", "");
        //                 } else if (replace_param1.match(/@GetAVG\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
        //                     replace_param1 = splitted_default_val[ctr].trim().match(/@GetAVG\((@[A-Za-z][A-Za-z0-9_]*)\)/);
        //                     replace_param1 = replace_param1[1].replace("@", "");
        //                 } else {
        //                     replace_param1 = splitted_default_val[ctr].trim().replace("@", "");
        //                 }
        //                 element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');

        //                 if ($(fieldWithComputation).parents("tr").length >= 1) {
        //                     if ($(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]').length >= 1) {
        //                         element_in_computation = $(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
        //                     } else if ($(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]').length >= 1) {
        //                         element_in_computation = $(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
        //                         // console.log($(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
        //                     } else {
        //                         element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
        //                     }
        //                 } else {
        //                     element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
        //                 }

        //                 if (element_in_computation.length >= 1) {
        //                 } else {
        //                     continue;
        //                 }

        //                 if (element_in_computation.attr("data-input-type") && element_in_computation.attr("data-input-type") == "Currency") {
        //                     replace_param2 = element_in_computation.val().replace(/,/g, "");
        //                 } else {
        //                     replace_param2 = element_in_computation.val();
        //                 }

        //                 if ($.isNumeric($.trim(replace_param2))) {

        //                 } else {
        //                     is_number = "false";
        //                     break;
        //                 }
        //             }
        //             for (ctr = 0; ctr < splitted_default_val.length; ctr++) {
        //                 replace_param1 = splitted_default_val[ctr].trim();
        //                 if (replace_param1.match(/@Sum\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {

        //                     var second_fn = "@Sum";
        //                 }
        //                 if (replace_param1.match(/@GetMax\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {
        //                     var second_fn = "@GetMax";
        //                 }
        //                 if (replace_param1.match(/@GetMin\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {

        //                     var second_fn = "@GetMin";
        //                 }
        //                 if (string_default_val.match(/@SDev\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {

        //                     var second_fn = "@SDev";
        //                 }
        //                 if (string_default_val.match(/@GetAVG\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {

        //                     var second_fn = "@GetAVG";
        //                 }
        //                 if ($(fieldWithComputation).parents("tr").length >= 1) {
        //                     if ($(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]').length >= 1) {
        //                         element_in_computation = $(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
        //                         // console.log($(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
        //                         // }else{
        //                         //     element_in_computation = $(fieldWithComputation).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
        //                         //     console.log($(fieldWithComputation).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
        //                         // }
        //                     } else if ($(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]').length >= 1) {
        //                         element_in_computation = $(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
        //                         // console.log($(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
        //                     } else {
        //                         element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
        //                     }
        //                 } else {
        //                     element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
        //                     // console.log($(fieldWithComputation).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
        //                 }
        //                 // element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
        //                 if (replace_param1 == "") {
        //                     continue;
        //                 }
        //                 if (element_in_computation.length >= 1 && (string_default_val.match(/@GetAVG/) == null && string_default_val.match(/@SDev/) == null && replace_param1.match(/@Sum/) == null && replace_param1.match(/@GetMax/) == null && replace_param1.match(/@GetMin/) == null)) {
        //                     var field_type = "";
        //                     if (typeof element_in_computation.attr("type") !== "undefined") {
        //                         if (element_in_computation.attr("type") == "radio") {
        //                             field_type = "radio";
        //                         }
        //                     }
        //                     if (element_in_computation.attr("data-input-type") && element_in_computation.attr("data-input-type") == "Currency") {
        //                         replace_param2 = element_in_computation.val().replace(/,/g, "");
        //                     } else {
        //                         if (field_type == "radio") {
        //                             replace_param2 = $('[name="' + element_in_computation.attr("name") + '"]:checked').val();
        //                             if (!replace_param2) {
        //                                 replace_param2 = "";
        //                             }
        //                         } else {
        //                             replace_param2 = element_in_computation.val();
        //                         }

        //                     }

        //                     if (is_number == "false") {
        //                         if (element_in_computation.attr("data-type") == "float") {
        //                             string_default_val = string_default_val.replace(replace_param1, "Number('" + "" + replace_param2.replace(/\"/g, "\\\"") + "" + "')");
        //                         } else if (element_in_computation.attr("data-type") == "longtext") {
        //                             replace_param2 = replace_param2.replace(/\\/g, "\\\\");
        //                             replace_param2 = replace_param2.replace(/\"/g, "\\\"");
        //                             // string_default_val = string_default_val.replace(replace_param1,"\""+replace_param2.replace(/\\/g,"\\\\")+"\"");
        //                             string_default_val = string_default_val.replace(replace_param1, "\"" + replace_param2 + "\"");
        //                         } else {
        //                             string_default_val = string_default_val.replace(replace_param1, "\"" + replace_param2.replace(/\"/g, "\\\"") + "\"");
        //                         }
        //                     } else {
        //                         string_default_val = string_default_val.replace(replace_param1, replace_param2);
        //                     }
        //                 } else if (element_in_computation.length == 0 || (string_default_val.match(/@SDev/) != null || replace_param1.match(/@Sum/) != null || replace_param1.match(/@GetMax/) != null || replace_param1.match(/@GetMin/) != null)) {

        //                     if (typeof second_fn !== "undefined") { //di na kailangan nito
        //                         // if(second_fn == "@Sum"){
        //                         //     replace_param1 = "@Sum("+replace_param1+")";
        //                         // }else if(second_fn == "@GetMax"){
        //                         //     replace_param1 = "@GetMax("+replace_param1+")";
        //                         // }else if(second_fn == "@GetMin"){
        //                         //     replace_param1 = "@GetMin("+replace_param1+")";
        //                         // }
        //                     }
        //                     if (replace_param1.indexOf("@Today") >= 0) {
        //                         var this_today = new Date(this_ini_variant.getUpdatedServerTime());
        //                         this_today = this_today.getFullYear() + "-" + StrRight("0" + (this_today.getMonth() + 1), 2) + "-" + StrRight("0" + this_today.getDate(), 2);
        //                         string_default_val = string_default_val.replace(replace_param1, "\"" + this_today + "\"");
        //                     } else if (replace_param1.indexOf("@Now") >= 0) {
        //                         var this_today = new Date(this_ini_variant.getUpdatedServerTime());
        //                         this_today = this_today.getFullYear() + "-" + StrRight("0" + (this_today.getMonth() + 1), 2) + "-" + StrRight("0" + this_today.getDate(), 2) + " " + StrRight("0" + this_today.getHours(), 2) + ":" + StrRight("0" + this_today.getMinutes(), 2) + ":" + StrRight("0" + this_today.getSeconds(), 2);
        //                         string_default_val = string_default_val.replace(replace_param1, "\"" + this_today + "\"");
        //                     } else if (replace_param1.indexOf("@RequestID") >= 0) {
        //                         var getID = $("#ID").val();
        //                         string_default_val = string_default_val.replace(replace_param1, "\"" + getID + "\"");
        //                     } else if (replace_param1.indexOf("@Department") >= 0) {
        //                         var getDepName = $("[name='Department_Name']").val();
        //                         string_default_val = string_default_val.replace(replace_param1, "\"" + getDepName + "\"");
        //                     } else if (replace_param1.match(/\[[A-Za-z]*\]/) != null) {//FOR SUM AVG ETC FORMULA
        //                         var fieldName = replace_param1.replace(/\[[A-Za-z]*\]|@/g, "");
        //                         var formula_function = replace_param1.match(/\[[A-Za-z]*\]/);
        //                         var get_fields_value = "(";
        //                         if (formula_function[0] == "[sum]") {
        //                             get_fields_value = get_fields_value + "Number('" + $('[name="' + fieldName + '"]').val() + "')";
        //                             $('[rep-original-name="' + fieldName + '"]').each(function() {
        //                                 get_fields_value = get_fields_value + " + Number('" + $(this).val() + "')";
        //                             });
        //                             get_fields_value = get_fields_value + ")";
        //                             string_default_val = string_default_val.replace(replace_param1, "" + get_fields_value + "");
        //                         }
        //                         if (formula_function[0] == "[Last]") {
        //                             if ($('[rep-original-name="' + fieldName + '"]').length >= 1) {
        //                                 var element_in_computation_last = $('[rep-original-name="' + fieldName + '"]').last();
        //                                 if ($.isNumeric(element_in_computation_last.val())) {
        //                                     get_fields_value = get_fields_value + "" + element_in_computation_last.val() + "";
        //                                 } else {
        //                                     get_fields_value = get_fields_value + "'" + element_in_computation_last.val() + "'";
        //                                 }
        //                                 get_fields_value = get_fields_value + ")";
        //                                 string_default_val = string_default_val.replace(replace_param1, "" + get_fields_value + "");
        //                             } else if ($('[name="' + fieldName + '"]').length >= 1) {
        //                                 var element_in_computation_last = $('[name="' + fieldName + '"]').last();
        //                                 if ($.isNumeric(element_in_computation_last.val())) {
        //                                     get_fields_value = get_fields_value + "" + element_in_computation_last.val() + "";
        //                                 } else {
        //                                     get_fields_value = get_fields_value + "'" + element_in_computation_last.val() + "'";
        //                                 }
        //                                 get_fields_value = get_fields_value + ")";
        //                                 string_default_val = string_default_val.replace(replace_param1, "" + get_fields_value + "");
        //                             }
        //                         }
        //                     } else if (replace_param1.match(/@Sum\(@[A-Za-z0-9_]*\)/g) != null) { //FOR @Sum(@Fieldname)
        //                         fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
        //                         var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
        //                         if (fieldExists("\"" + fieldName[1] + "\"") == true) {
        //                             string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
        //                         }
        //                     } else if (replace_param1.match(/@GetMax\(@[A-Za-z0-9_]*\)/g) != null) { //

        //                         fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
        //                         var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
        //                         if (fieldExists("\"" + fieldName[1] + "\"") == true) {
        //                             string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
        //                         }
        //                     } else if (replace_param1.match(/@GetMin\(@[A-Za-z0-9_]*\)/g) != null) { //
        //                         fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
        //                         var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
        //                         if (fieldExists("\"" + fieldName[1] + "\"") == true) {
        //                             string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
        //                         }
        //                     } else if (replace_param1.match(/@SDev\(@[A-Za-z0-9_]*\)/g) != null) { //
        //                         fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
        //                         var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
        //                         if (fieldExists("\"" + fieldName[1] + "\"") == true) {
        //                             string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
        //                         }
        //                     } else if (replace_param1.match(/@GetAVG\(@[A-Za-z0-9_]*\)/g) != null) { //

        //                         fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
        //                         var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
        //                         if (fieldExists("\"" + fieldName[1] + "\"") == true) {
        //                             string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
        //                         }

        //                     }
        //                 }
        //             }
        //             if (string_default_val.indexOf("@") >= 0) {
        //                 string_default_val = string_default_val.replace(/@/g, "");
        //             }
        //             if (string_default_val.indexOf(/\'/g) >= 0) {
        //                 string_default_val = string_default_val.replace(/\'/g, "\'");
        //             }
        //             // console.log(string_default_val)
        //             // if(string_default_val.match(/\\/g) != null){
        //             //  string_default_val = string_default_val.replace(/\\/g,"\\\\");
        //             // }
        //             // console.log(string_default_val)
        //             if (string_default_val.match(/\"/g) != null) {
        //                 string_default_val = string_default_val.replace(/\"/g, "\"");
        //             }
        //             // console.log("TEST")
        //             // console.log(string_default_val)
        //             var eval_status = "not ok";
        //             try {
        //                 eval(string_default_val);
        //                 eval_status = "ok";
        //                 // console.log("OK",string_default_val,fieldWithComputation)
        //             } catch (error) {
        //                 eval_status = "not ok";
        //                 // console.log("NOT OK",string_default_val,fieldWithComputation,error);
        //             }
        //             // console.log("NAKARATING??")
        //             // console.log(fieldWithComputation)
        //             // console.log($(this))
        //             if (eval_status == "ok") {
        //                 if (string_default_val.indexOf("Lookup") >= 0) {
        //                     //data = [];
        //                     //fieldName = fieldWithComputation.attr("name");
        //                     //formula = string_default_val;
        //                     //data.push({
        //                     //    FieldName: fieldName,
        //                     //    Formula: formula
        //                     //});
        //                     //$.get('/ajax/ajaxformula', {
        //                     //    data: JSON.stringify(data)
        //                     //}, function(data) {
        //                     //    data = JSON.parse(data);
        //                     //    console.log("uung sa onchange");
        //                     //    console.log(data);
        //                     //    $('[name="' + data[0].FieldName + '"]').val(data[0].FieldValue);
        //                     //});
        //                 } else if (string_default_val.indexOf("RecordCount") >= 0) {
        //                     //
        //                 } else {
        //                     if (eval(string_default_val) == "Infinity") {
        //                         fieldWithComputation.val("Cannot divide by zero");
        //                     } else if (eval(string_default_val) == "Invalid Date") {
        //                         //do not place any value
        //                     } else {
        //                         if (fieldWithComputation.hasClass("hasDatepicker") && fieldWithComputation.attr("data-type") == "date") {
        //                             fieldWithComputation.val(eval(string_default_val));
        //                             fieldWithComputation.val(ThisDate(fieldWithComputation.val()).formatDate("Y-m-d"));
        //                         } else if (fieldWithComputation.hasClass("hasDatepicker") && fieldWithComputation.attr("data-type") == "dateTime") {
        //                             fieldWithComputation.val(eval(string_default_val));
        //                             fieldWithComputation.val(ThisDate(fieldWithComputation.val()).formatDate("Y-m-d H:i"));
        //                         } else {
        //                             fieldWithComputation.val(eval(string_default_val));
        //                             if (fieldWithComputation.val() == "NaN") {
        //                                 fieldWithComputation.val("Not a valid computation")
        //                             }
        //                         }
        //                     }
        //                 }
        //             } else {
        //                 //console.log(fieldWithComputation,"EVAL STAT NOT OK");
        //                 //console.log(string_default_val)
        //             }


        //             // }catch(error){
        //             //   alert("nag error??")
        //             // }
        //             // if(fieldWithComputation.attr("default-formula-value").indexOf("GivenIf") >= 0 ){
        //             //   fieldWithComputation.change();
        //             // }
        //             var reg_eks = new RegExp("@" + fieldWithComputation.attr("name") + "(?![a-zA-Z0-9_])", "g");
        //             if (fieldWithComputation.attr("default-formula-value").match(reg_eks) == null) {
        //                 fieldWithComputation.change();
        //             }
        //             //console.log(string_default_val)
        //             //console.log("\n\n\n\n\n\n\n\n\n\n\n\n")
        //         });
        //         //}
        //     }

        // },
        "makeOnChange": function(fieldAffected, fieldWithComputationParam, eventAddressNamespace) {
            var fieldname_keywords = [
                "FormID", "WorkflowId", "ID",
                "Requestor", "CurrentUser", "Status",
                "Processor", "LastAction", "DateCreated",
                "DateUpdated", "CreatedBy", "UpdatedBy",
                "Unread", "Node_ID", "Workflow_ID",
                "Mode", "TrackNo", "imported",
                "computedFields", "fieldEnabled", "KeywordsField",
                "Repeater_Data", "Department_Name", "From",
                "To", "Range", "requestorname","Auth"
            ];
            var this_ini_variant = this;
            var fieldWithComputation = $(fieldWithComputationParam);
            // console.log("check affected")
            // console.log(fieldAffected)
            if (fieldWithComputation.attr("default-formula-value")) {
                var event_string = "keyup change";
                // var field_affected = $(fieldAffected);
                // var field_typing = field_affected.filter(function(index, elem){
                //     if($(elem).prop("tagName") == "TEXTAREA") {
                //         return true;
                //     }else if($(elem).attr("type")){
                //         if($(elem).attr("type") == "text" && !$(elem).hasClass("hasDatepicker")){
                //             return true;
                //         }
                //     }
                // });
                // if(field_typing.length >= 1 ){
                //     var event_string = "keyup";
                // }else{
                //     var event_string = "change";
                // }

                if (typeof eventAddressNamespace == "undefined") {
                    //do nothing

                } else {
                    event_string = "keyup." + eventAddressNamespace + " change." + eventAddressNamespace;//namespace added for destroying repeated events
                    // var field_affected = $(fieldAffected);
                    // if(
                    //     field_affected.prop("tagName") == "TEXTAREA" ||
                    //     field_affected.attr("type") == "text"
                    // ){
                    //     event_string = "keyup." + eventAddressNamespace;
                    // }else{
                    //     event_string = "change." + eventAddressNamespace;
                    // }
                }
                // console.log(event_string)
                // console.log("eto na ba un")
                // console.log(fieldAffected)
                if ($(fieldAffected).attr("event-id-from")) {
                    var ids_event_from = $(fieldAffected).attr("event-id-from");
                    var array_ids_event_from = ids_event_from.split(",");
                    if (array_ids_event_from.indexOf(fieldWithComputation.closest(".setOBJ").attr("data-object-id")) >= 0) {

                    } else {
                        $(fieldAffected).attr("event-id-from", $(fieldAffected).attr("event-id-from") + "," + fieldWithComputation.closest(".setOBJ").attr("data-object-id"));
                    }
                } else {
                    //console.log($(fieldAffected).attr("event-id-from", "" + fieldWithComputation.closest(".setOBJ").attr("data-object-id")));
                }
                // console.log("HAYS")
                // console.log(fieldWithComputation)

                $(fieldAffected).on(event_string, {"fieldWithComputation": fieldWithComputation}, function(e) {
                    var fieldname_keywords = [
                        "FormID", "WorkflowId", "ID",
                        "Requestor", "CurrentUser", "Status",
                        "Processor", "LastAction", "DateCreated",
                        "DateUpdated", "CreatedBy", "UpdatedBy",
                        "Unread", "Node_ID", "Workflow_ID",
                        "Mode", "TrackNo", "imported",
                        "computedFields", "fieldEnabled", "KeywordsField",
                        "Repeater_Data", "Department_Name", "From",
                        "To", "Range", "requestorname","Auth"
                    ];
                    // alert("KULANGOT")
                    // e.stopPropagation();//AYAW GUMANA :<<<
                    // event.stopPropagation();//AYAW GUMANA :<<<
                    var fieldWithComputation = e.data.fieldWithComputation;
                    // try{
                    // console.log("ETO NGA BA UN?")
                    // console.log(fieldWithComputation)
                    var string_default_val = "" + fieldWithComputation.attr("default-formula-value");
                    // console.log("eto ung formula")
                    // console.log(string_default_val)
                    // console.log(fieldWithComputation)
                    if (string_default_val.indexOf("@Lookup") >= 0) {
                        return;
                    }
                    if (string_default_val.indexOf("@LookupWhere") >= 0) {
                        return;
                    }
                    if (string_default_val.indexOf("@LookupGetMin") >= 0) {
                        return;
                    }
                    if (string_default_val.indexOf("@LookupGetMax") >= 0) {
                        return;
                    }
                    if (string_default_val.indexOf("@LookupSDev") >= 0) {
                        return;
                    }
                    if (string_default_val.indexOf("@LookupAVG") >= 0) {
                        return;
                    }
                    if (string_default_val.indexOf(/^@Total\(*.\)$/) >= 0) {
                        return;
                    }
                    var string_field_formula = string_default_val;
                    try {
                        splitted_default_val = string_default_val.match(/@GetAVG\(@[A-Za-z0-9_]*\)|@SDev\(@[A-Za-z0-9_]*\)|@GetMin\(@[A-Za-z0-9_]*\)|@GetMax\(@[A-Za-z0-9_]*\)|@Sum\(@[A-Za-z0-9_]*\)|@(\[[a-zA-Z0-9_\'\"]*\]){3}|@[A-Za-z0-9_]*/g);
                    } catch (error) {
                        //console.log("the formula value is not defined");
                    }
                    var is_number = "true";
                    for (ctr = 0; ctr < splitted_default_val.length; ctr++) {
                        replace_param1 = splitted_default_val[ctr].trim();
                        if (replace_param1.match(/@Sum\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
                            replace_param1 = splitted_default_val[ctr].trim().match(/@Sum\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                            replace_param1 = replace_param1[1].replace("@", "");
                        } else if (replace_param1.match(/@GetMax\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
                            replace_param1 = splitted_default_val[ctr].trim().match(/@GetMax\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                            replace_param1 = replace_param1[1].replace("@", "");
                        } else if (replace_param1.match(/@GetMin\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
                            replace_param1 = splitted_default_val[ctr].trim().match(/@GetMin\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                            replace_param1 = replace_param1[1].replace("@", "");
                        } else if (replace_param1.match(/@SDev\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
                            replace_param1 = splitted_default_val[ctr].trim().match(/@SDev\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                            replace_param1 = replace_param1[1].replace("@", "");
                        } else if (replace_param1.match(/@GetAVG\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
                            replace_param1 = splitted_default_val[ctr].trim().match(/@GetAVG\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                            replace_param1 = replace_param1[1].replace("@", "");
                        } else {
                            replace_param1 = splitted_default_val[ctr].trim().replace("@", "");
                        }

                        element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');

                        if ($(fieldWithComputation).parents("tr").length >= 1) {
                            if ($(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]').length >= 1) {
                                element_in_computation = $(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                            } else if ($(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]').length >= 1) {
                                element_in_computation = $(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                                // console.log($(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
                            } else {
                                element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                            }
                        } else {
                            element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                        }

                        if (element_in_computation.length >= 1) {
                        } else {
                            continue;
                        }

                        if (element_in_computation.attr("data-input-type") && element_in_computation.attr("data-input-type") == "Currency") {
                            replace_param2 = element_in_computation.val().replace(/,/g, "");
                        } else {
                            replace_param2 = element_in_computation.val();
                        }

                        if ($.isNumeric($.trim(replace_param2))) {

                        } else {
                            is_number = "false";
                            break;
                        }
                    }
                    for (ctr = 0; ctr < splitted_default_val.length; ctr++) {
                        replace_param1 = splitted_default_val[ctr].trim();
                        if (replace_param1.match(/@Sum\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {

                            var second_fn = "@Sum";
                        }
                        if (replace_param1.match(/@GetMax\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {
                            var second_fn = "@GetMax";
                        }
                        if (replace_param1.match(/@GetMin\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {

                            var second_fn = "@GetMin";
                        }
                        if (string_default_val.match(/@SDev\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {

                            var second_fn = "@SDev";
                        }
                        if (string_default_val.match(/@GetAVG\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null) {

                            var second_fn = "@GetAVG";
                        }
                        if ($(fieldWithComputation).parents("tr").length >= 1) {
                            if ($(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]').length >= 1) {
                                element_in_computation = $(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                                // console.log($(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
                                // }else{
                                //     element_in_computation = $(fieldWithComputation).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                                //     console.log($(fieldWithComputation).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
                                // }
                            } else if ($(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]').length >= 1) {
                                element_in_computation = $(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                                // console.log($(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
                            } else {
                                element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                            }
                        } else {
                            element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                            // console.log($(fieldWithComputation).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
                        }
                        // element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                        if (replace_param1 == "") {
                            continue;
                        }
                        // console.log("WORMHOLDE",splitted_default_val[ctr].replace("@", "") , fieldname_keywords, fieldname_keywords.indexOf(splitted_default_val[ctr].replace("@", "")) , fieldname_keywords.indexOf(splitted_default_val[ctr].replace("@", "")) <= -1);
                        if (element_in_computation.length >= 1 && fieldname_keywords.indexOf(splitted_default_val[ctr].replace("@", "")) <= -1 && (string_default_val.match(/@GetAVG/) == null && string_default_val.match(/@SDev/) == null && replace_param1.match(/@Sum/) == null && replace_param1.match(/@GetMax/) == null && replace_param1.match(/@GetMin/) == null)) {
                            var field_type = "";
                            if (typeof element_in_computation.attr("type") !== "undefined") {
                                if (element_in_computation.attr("type") == "radio") {
                                    field_type = "radio";
                                }
                            }
                            if (element_in_computation.attr("data-input-type") && element_in_computation.attr("data-input-type") == "Currency") {
                                replace_param2 = element_in_computation.val().replace(/,/g, "");
                            } else {
                                if (field_type == "radio") {
                                    replace_param2 = $('[name="' + element_in_computation.attr("name") + '"]:checked').val();
                                    if (!replace_param2) {
                                        replace_param2 = "";
                                    }
                                } else {
                                    replace_param2 = element_in_computation.val();
                                }

                            }

                            if (is_number == "false") {
                                if (element_in_computation.attr("data-type") == "float" || element_in_computation.attr("data-type") == "double") {
                                    string_default_val = string_default_val.replace(replace_param1, "Number('" + "" + replace_param2.replace(/\"/g, "\\\"") + "" + "')");
                                } else if (element_in_computation.attr("data-type") == "longtext") {
                                    replace_param2 = replace_param2.replace(/\\/g, "\\\\");
                                    replace_param2 = replace_param2.replace(/\"/g, "\\\"");
                                    // string_default_val = string_default_val.replace(replace_param1,"\""+replace_param2.replace(/\\/g,"\\\\")+"\"");
                                    string_default_val = string_default_val.replace(replace_param1, "\"" + replace_param2 + "\"");
                                } else {
                                    string_default_val = string_default_val.replace(replace_param1, "\"" + replace_param2.replace(/\"/g, "\\\"") + "\"");
                                }
                            } else {
                                string_default_val = string_default_val.replace(replace_param1, replace_param2);
                            }
                        } else if (element_in_computation.length == 0 || fieldname_keywords.indexOf(splitted_default_val[ctr].replace("@", "")) >= 0 || (string_default_val.match(/@GetAVG/) != null || string_default_val.match(/@SDev/) != null || replace_param1.match(/@Sum/) != null || replace_param1.match(/@GetMax/) != null || replace_param1.match(/@GetMin/) != null)) {
                            if (typeof second_fn !== "undefined") { //di na kailangan nito
                                // if(second_fn == "@Sum"){
                                //     replace_param1 = "@Sum("+replace_param1+")";
                                // }else if(second_fn == "@GetMax"){
                                //     replace_param1 = "@GetMax("+replace_param1+")";
                                // }else if(second_fn == "@GetMin"){
                                //     replace_param1 = "@GetMin("+replace_param1+")";
                                // }
                            }
                            if (replace_param1.indexOf("@Today") >= 0) {
                                var this_today = new Date(this_ini_variant.getUpdatedServerTime());
                                this_today = this_today.getFullYear() + "-" + StrRight("0" + (this_today.getMonth() + 1), 2) + "-" + StrRight("0" + this_today.getDate(), 2);
                                string_default_val = string_default_val.replace(replace_param1, "\"" + this_today + "\"");
                            } else if (replace_param1.indexOf("@Now") >= 0) {
                                var this_today = new Date(this_ini_variant.getUpdatedServerTime());
                                this_today = this_today.getFullYear() + "-" + StrRight("0" + (this_today.getMonth() + 1), 2) + "-" + StrRight("0" + this_today.getDate(), 2) + " " + StrRight("0" + this_today.getHours(), 2) + ":" + StrRight("0" + this_today.getMinutes(), 2) + ":" + StrRight("0" + this_today.getSeconds(), 2);
                                string_default_val = string_default_val.replace(replace_param1, "\"" + this_today + "\"");
                            } else if (replace_param1.indexOf("@RequestID") >= 0) {
                                var getID = $("#ID").val();
                                string_default_val = string_default_val.replace(replace_param1, "\"" + getID + "\"");
                            } else if (replace_param1.indexOf("@Status") >= 0) {
                                var stat = $("[name='Status']").val();
                                string_default_val = string_default_val.replace(replace_param1, "\"" + stat + "\"");
                            } else if (replace_param1.indexOf("@Processor") >= 0) {
                                if ($("[name='ID']").val() == "0") {
                                    var processor_user_ele = $('[name="Processor"]');
                                    var processor_name = processor_user_ele.attr("processor-name");
                                } else {
                                    var processor_user_ele = $("#processor_display");
                                    var processor_name = processor_user_ele.text();
                                }

                                // var getCurrentUser = "<?php echo $auth['display_name']; ?>";
                                // string_default_val = string_default_val.replace(replace_param1, "\"" + getCurrentUser + "\"");
                                string_default_val = string_default_val.replace(replace_param1, "\"" + processor_name + "\"");
                            } else if (replace_param1.indexOf("@Department") >= 0) {
                                var getDepName = $("[name='Department_Name']").val();
                                string_default_val = string_default_val.replace(replace_param1, "\"" + getDepName + "\"");
                            // } else if (replace_param1.match(/\[[A-Za-z]*\]/) != null) {//FOR SUM AVG ETC FORMULA
                            //     var fieldName = replace_param1.replace(/\[[A-Za-z]*\]|@/g, "");
                            //     var formula_function = replace_param1.match(/\[[A-Za-z]*\]/);
                            //     var get_fields_value = "(";
                            //     if (formula_function[0] == "[sum]") {
                            //         get_fields_value = get_fields_value + "Number('" + $('[name="' + fieldName + '"]').val() + "')";
                            //         $('[rep-original-name="' + fieldName + '"]').each(function() {
                            //             get_fields_value = get_fields_value + " + Number('" + $(this).val() + "')";
                            //         });
                            //         get_fields_value = get_fields_value + ")";
                            //         string_default_val = string_default_val.replace(replace_param1, "" + get_fields_value + "");
                            //     }
                            //     if (formula_function[0] == "[Last]") {
                            //         if ($('[rep-original-name="' + fieldName + '"]').length >= 1) {
                            //             var element_in_computation_last = $('[rep-original-name="' + fieldName + '"]').last();
                            //             if ($.isNumeric(element_in_computation_last.val())) {
                            //                 get_fields_value = get_fields_value + "" + element_in_computation_last.val() + "";
                            //             } else {
                            //                 get_fields_value = get_fields_value + "'" + element_in_computation_last.val() + "'";
                            //             }
                            //             get_fields_value = get_fields_value + ")";
                            //             string_default_val = string_default_val.replace(replace_param1, "" + get_fields_value + "");
                            //         } else if ($('[name="' + fieldName + '"]').length >= 1) {
                            //             var element_in_computation_last = $('[name="' + fieldName + '"]').last();
                            //             if ($.isNumeric(element_in_computation_last.val())) {
                            //                 get_fields_value = get_fields_value + "" + element_in_computation_last.val() + "";
                            //             } else {
                            //                 get_fields_value = get_fields_value + "'" + element_in_computation_last.val() + "'";
                            //             }
                            //             get_fields_value = get_fields_value + ")";
                            //             string_default_val = string_default_val.replace(replace_param1, "" + get_fields_value + "");
                            //         }
                            //     }
                            } else if (replace_param1.match(/@Sum\(@[A-Za-z0-9_]*\)/g) != null) { //FOR @Sum(@Fieldname)
                                fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
                                var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
                                if (fieldExists("\"" + fieldName[1] + "\"") == true) {
                                    string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                                }

                            } else if (replace_param1.match(/@GetMax\(@[A-Za-z0-9_]*\)/g) != null) { //

                                fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
                                var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
                                if (fieldExists("\"" + fieldName[1] + "\"") == true) {
                                    string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                                }

                            } else if (replace_param1.match(/@GetMin\(@[A-Za-z0-9_]*\)/g) != null) { //
                                fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
                                var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
                                if (fieldExists("\"" + fieldName[1] + "\"") == true) {
                                    string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                                }

                            } else if (replace_param1.match(/@SDev\(@[A-Za-z0-9_]*\)/g) != null) { //
                                fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
                                var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
                                if (fieldExists("\"" + fieldName[1] + "\"") == true) {
                                    string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                                }

                            } else if (replace_param1.match(/@GetAVG\(@[A-Za-z0-9_]*\)/g) != null) { //

                                fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
                                var reg_exp = new RegExp(fieldName[1] + "|" + "'" + fieldName[1] + "'", 'g');
                                if (fieldExists("\"" + fieldName[1] + "\"") == true) {
                                    string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                                }

                            } else if (splitted_default_val[ctr].match(/@(\[[a-zA-Z0-9_\'\"]*\]){3}/g) != null){
                                var reg_exp = new RegExp("\\[[@a-zA-Z0-9_\\\'\\\"]*\\](?!\\s)", 'g');
                                var value_get = "";
                                if(splitted_default_val[ctr].match(reg_exp) != null){
                                    var match_res = splitted_default_val[ctr].match(reg_exp).filter(Boolean);
                                    var tbl_name = match_res[0].replace(/\[|\]/g,"");
                                    var field_name = match_res[1].replace(/\[|\]/g,"");
                                    var fn_index = match_res[2].replace(/\[|\]/g,"");
                                    if($.isNumeric(fn_index)){
                                        var collect_fn_ele = $('[table-name="'+tbl_name+'"]').find('[name="'+field_name+'"]');
                                        collect_fn_ele = collect_fn_ele.add($('[table-name="'+tbl_name+'"]').find('[rep-original-name="'+field_name+'"]'));
                                        if(collect_fn_ele.eq(fn_index).attr("data-type") == "float" || collect_fn_ele.eq(fn_index).attr("data-type") == "double"){
                                            value_get = "Number("+collect_fn_ele.eq(fn_index).val()+")";
                                        }else{
                                            value_get = "\'"+collect_fn_ele.eq(fn_index).val()+"\'";
                                        }
                                    }else if(fn_index == "RootRowIndex"){
                                        fn_index = GetRowIndex($(fieldWithComputation.parents(".setOBJ").eq(0)));
                                        console.log("fn_index",fn_index,$(fieldWithComputation.parents(".setOBJ").eq(0)))
                                        var collect_fn_ele = $('[table-name="'+tbl_name+'"]').find('[name="'+field_name+'"]');
                                        collect_fn_ele = collect_fn_ele.add($('[table-name="'+tbl_name+'"]').find('[rep-original-name="'+field_name+'"]'));
                                        if(collect_fn_ele.eq(fn_index).attr("data-type") == "float" || collect_fn_ele.eq(fn_index).attr("data-type") == "double"){
                                            value_get = "Number("+collect_fn_ele.eq(fn_index).val()+")";
                                        }else{
                                            value_get = "\'"+collect_fn_ele.eq(fn_index).val()+"\'";
                                        }
                                    }else if(fn_index == "RowIndex"){
                                        // fn_index = GetRowIndex($('[table-name="'+tbl_name+'"]').find('[name="'+field_name+'"]'));

                                        // var collect_fn_ele = $('[table-name="'+tbl_name+'"]').find('[name="'+field_name+'"]');
                                        // collect_fn_ele = collect_fn_ele.add($('[table-name="'+tbl_name+'"]').find('[rep-original-name="'+field_name+'"]'));
                                        // if(collect_fn_ele.eq(fn_index).attr("data-type") == "float"){
                                        //     value_get = "Number("+collect_fn_ele.eq(fn_index).val()+")";
                                        // }else{
                                        //     value_get = "\'"+collect_fn_ele.eq(fn_index).val()+"\'";
                                        // }
                                    }
                                }
                                var reg_exp_repl = new RegExp(splitted_default_val[ctr].replace(/\[/g,"\\\[").replace(/\]/g,"\\\]").replace(/\'/g,"\\\'").replace(/\"/g,"\\\""),"g");
                                string_default_val = string_default_val.replace(reg_exp_repl, value_get);

                            }
                            //console.log("BADDDKERT", replace_param1);
                        }
                    }
                    if (string_default_val.indexOf("@") >= 0) {
                        string_default_val = string_default_val.replace(/@/g, "");
                    }
                    if (string_default_val.indexOf(/\'/g) >= 0) {
                        string_default_val = string_default_val.replace(/\'/g, "\'");
                    }
                    // console.log(string_default_val)
                    // if(string_default_val.match(/\\/g) != null){
                    //  string_default_val = string_default_val.replace(/\\/g,"\\\\");
                    // }
                    // console.log(string_default_val)
                    if (string_default_val.match(/\"/g) != null) {
                        string_default_val = string_default_val.replace(/\"/g, "\"");
                    }
                    if (string_default_val.match(/\n/g) != null) {
                        //string_default_val = string_default_val.replace(/\n/g, "\\n");
                    }
                    //console.log("TEST")
                    console.log("TEST FORMULA",string_default_val,"\nDIS",$(this),"\nLOCATION F",fieldWithComputation);
                    var eval_status = "not ok";
                    try {
                        eval(string_default_val);
                        eval_status = "ok";
                         console.log("OK",string_default_val,fieldWithComputation)
                    } catch (error) {
                        eval_status = "not ok";
                         console.log("NOT OK",string_default_val,fieldWithComputation,error);
                    }
                    // console.log("NAKARATING??")
                    // console.log(fieldWithComputation)
                    // console.log($(this))
                    if (eval_status == "ok") {
                        if (string_default_val.indexOf("Lookup") >= 0) {
                            //data = [];
                            //fieldName = fieldWithComputation.attr("name");
                            //formula = string_default_val;
                            //data.push({
                            //    FieldName: fieldName,
                            //    Formula: formula
                            //});
                            //$.get('/ajax/ajaxformula', {
                            //    data: JSON.stringify(data)
                            //}, function(data) {
                            //    data = JSON.parse(data);
                            //    console.log("uung sa onchange");
                            //    console.log(data);
                            //    $('[name="' + data[0].FieldName + '"]').val(data[0].FieldValue);
                            //});
                        } else if (string_default_val.indexOf("RecordCount") >= 0) {
                            //
                        } else {
                            if (eval(string_default_val) == "Infinity") {
                                fieldWithComputation.val("Cannot divide by zero");
                            } else if (eval(string_default_val) == "Invalid Date") {
                                //do not place any value
                            } else {
                                if (fieldWithComputation.hasClass("hasDatepicker") && fieldWithComputation.attr("data-type") == "date") {
                                    fieldWithComputation.val(eval(string_default_val));
                                    fieldWithComputation.val(ThisDate(fieldWithComputation.val()).formatDate("Y-m-d"));
                                } else if (fieldWithComputation.hasClass("hasDatepicker") && fieldWithComputation.attr("data-type") == "dateTime") {
                                    fieldWithComputation.val(eval(string_default_val));
                                    fieldWithComputation.val(ThisDate(fieldWithComputation.val()).formatDate("Y-m-d H:i"));
                                } else {
                                    fieldWithComputation.val(eval(string_default_val));
                                    if (fieldWithComputation.val() == "NaN") {
                                        fieldWithComputation.val("Not a valid computation")
                                    }
                                }
                            }
                        }
                    } else {
                        //console.log(fieldWithComputation,"EVAL STAT NOT OK");
                        //console.log(string_default_val)
                    }


                    // }catch(error){
                    //   alert("nag error??")
                    // }
                    var reg_eks = new RegExp("@" + fieldWithComputation.attr("name") + "(?![a-zA-Z0-9_])", "g");
                    if (fieldWithComputation.attr("default-formula-value").match(reg_eks) == null) {
                        fieldWithComputation.change();
                    }
                    //console.log(string_default_val)
                    //console.log("\n\n\n\n\n\n\n\n\n\n\n\n")
                });
                //}
            }

        },
        // getData: function() {
        //     var repeaterData = [];
        //     $('[repeater-table="true"]').each(function() {
        //         var objectId = $(this).closest('.setOBJ').attr('id');
        //         var row = [];

        //         $(this).find('tr').each(function(index) {
        //             var data = [];

        //             $(this).find('.getFields').each(function() {
        //                 var originalName = $(this).attr('rep-original-name');
        //                 var name = $(this).attr('name');
        //                 var type = $(this).attr('type');

        //                 switch (type) {
        //                     case "checkbox":
        //                         var values = [];
        //                         if ($(this).prop('checked')) {
        //                             values.push({
        //                                 Value: $(this).val(),
        //                                 Checked: true
        //                             });
        //                         } else {
        //                             values.push({
        //                                 Value: $(this).val(),
        //                                 Checked: false
        //                             });
        //                         }
        //                         break;
        //                     case "radio":
        //                         var values = [];
        //                         if ($(this).prop('checked')) {
        //                             values.push({
        //                                 Value: $(this).val(),
        //                                 Checked: true
        //                             });
        //                         } else {
        //                             values.push({
        //                                 Value: $(this).val(),
        //                                 Checked: false
        //                             });
        //                         }
        //                         break;
        //                     default :
        //                         if (typeof $(this).attr("data-input-type") != "undefined") {
        //                             if ($(this).attr("data-input-type") == "Currency") {
        //                                 var values = $(this).val().replace(/,/g, "");
        //                             } else {
        //                                 var values = $(this).val();
        //                             }
        //                         } else {
        //                             var values = $(this).val();
        //                         }
        //                         break;
        //                 }
        //                 if (index === 0) {
        //                     data.push({
        //                         FieldName: name,
        //                         Values: values
        //                     });
        //                 } else {
        //                     data.push({
        //                         FieldName: originalName,
        //                         Values: values
        //                     });
        //                 }
        //             });

        //             row.push({
        //                 Index: index,
        //                 Data: data
        //             });
        //         });


        //         repeaterData.push({
        //             ObjectId: objectId,
        //             Row: row
        //         });
        //     });

        //     console.log('REPEATER GET DATA',repeaterData);

        //     $('#Repeater_Data').val(JSON.stringify(repeaterData));
        // },
        // setData: function() {
        //     try {
        //         var content = JSON.parse($('#Repeater_Data').val());


        //         for (var index in content) {
        //             var objectId = content[index].ObjectId;
        //             for (var row in content[index].Row) {
        //                 if (row != 0) {
        //                     $('#' + objectId).find('.rep-add-spec-row:last').click();
        //                     $('#' + objectId).find('.rep-add-spec-row:last').parents("tbody").eq(0).children("tr").last().children("td").stop(true, true);
        //                 }
        //                 for (var data in content[index].Row[row].Data) {

        //                     var fieldName = content[index].Row[row].Data[data].FieldName;
        //                     var type = $('[name="' + fieldName + '"]').attr('type');
        //                     var field;
        //                     var values;

        //                     if (row == 0) {
        //                         field = $('[name="' + fieldName + '"]');
        //                     } else {
        //                         field = $('[name="' + fieldName + '_UID' + row + '"]');
        //                     }

        //                     switch (type) {
        //                         case "checkbox":
        //                             var values = content[index].Row[row].Data[data].Values[0].Value;
        //                             var checked = content[index].Row[row].Data[data].Values[0].Checked;
        //                             $(field).each(function() {
        //                                 var thisValue = $(this).val();

        //                                 if (values == thisValue) {
        //                                     $(this).prop('checked', checked);
        //                                 }

        //                             });
        //                             break;
        //                         case "radio":
        //                             var values = content[index].Row[row].Data[data].Values[0].Value;
        //                             var checked = content[index].Row[row].Data[data].Values[0].Checked;

        //                             $(field).each(function() {
        //                                 var thisValue = $(this).val();
        //                                 if (values == thisValue) {
        //                                     $(this).prop('checked', checked);
        //                                 }
        //                             });
        //                             break;
        //                         default :
        //                             values = content[index].Row[row].Data[data].Values;
        //                             $(field).val(values);
        //                             break;
        //                     }

        //                 }
        //             }
        //         }
        //     } catch (error) {
        //         console.log("error setData: function() { parsing json")
        //     }
        // },
        getData: function() {
            var repeaterData = [];
            $('[repeater-table="true"]').each(function() {
                var objectId = $(this).closest('.setOBJ').attr('id');
                var row = [];

                $(this).find('tr').each(function(index) {
                    var data = [];

                    $(this).find('.getFields').each(function() {
                        var originalName = $(this).attr('rep-original-name');
                        var name = $(this).attr('name');
                        var type = $(this).attr('type');

                        switch (type) {
                            case "checkbox":
                                var values = [];
                                if ($(this).prop('checked')) {
                                    values.push({
                                        Value: $(this).val(),
                                        Checked: true
                                    });
                                } else {
                                    values.push({
                                        Value: $(this).val(),
                                        Checked: false
                                    });
                                }
                                break;
                            case "radio":
                                var values = [];
                                if ($(this).prop('checked')) {
                                    values.push({
                                        Value: $(this).val(),
                                        Checked: true
                                    });
                                } else {
                                    values.push({
                                        Value: $(this).val(),
                                        Checked: false
                                    });
                                }
                                break;
                            default :
                                if (typeof $(this).attr("data-input-type") != "undefined") {
                                    if ($(this).attr("data-input-type") == "Currency") {
                                        var values = $(this).val().replace(/,/g, "");
                                    } else {
                                        var values = $(this).val();
                                    }
                                } else {
                                    var values = $(this).val();
                                }
                                break;
                        }
                        if (index === 0) {
                            data.push({
                                FieldName: name,
                                Values: values
                            });
                        } else {
                            data.push({
                                FieldName: originalName,
                                Values: values
                            });
                        }
                    });

                    row.push({
                        Index: index,
                        Data: data
                    });
                });


                repeaterData.push({
                    ObjectId: objectId,
                    Row: row
                });
            });

            console.log('REPEATER GET DATA', repeaterData);

            $('#Repeater_Data').val(JSON.stringify(repeaterData));
        },
        setData: function() {
            try {
                var content = JSON.parse($('#Repeater_Data').val());


                for (var index in content) {
                    var objectId = content[index].ObjectId;
                    for (var row in content[index].Row) {
                        if (row != 0) {
                            $('#' + objectId).find('.rep-add-spec-row:last').click();
                            $('#' + objectId).find('.rep-add-spec-row:last').parents("tbody").eq(0).children("tr").last().children("td").stop(true, true);
                        }
                        for (var data in content[index].Row[row].Data) {

                            var fieldName = content[index].Row[row].Data[data].FieldName;
                            var type = $('[name="' + fieldName + '"]').attr('type');
                            var field;
                            var values;

                            if (row == 0) {
                                field = $('[name="' + fieldName + '"]');
                            } else {
                                field = $('[name="' + fieldName + '_UID' + row + '"]');
                            }

                            switch (type) {
                                case "checkbox":
                                    var values = content[index].Row[row].Data[data].Values[0].Value;
                                    var checked = content[index].Row[row].Data[data].Values[0].Checked;
                                    $(field).each(function() {
                                        var thisValue = $(this).val();

                                        if (values == thisValue) {
                                            $(this).prop('checked', checked);
                                        }

                                    });
                                    break;
                                case "radio":
                                    var values = content[index].Row[row].Data[data].Values[0].Value;
                                    var checked = content[index].Row[row].Data[data].Values[0].Checked;

                                    $(field).each(function() {
                                        var thisValue = $(this).val();
                                        if (values == thisValue) {
                                            $(this).prop('checked', checked);
                                        }
                                    });
                                    break;
                                default :
                                    values = content[index].Row[row].Data[data].Values;
                                    $(field).val(values);
                                    break;
                            }

                        }
                    }
                }
            } catch (error) {
                console.log("error setData: function() { parsing json")
            }
        },
        "getFormJson": function(form_id) {
            // form_id = $("#FormID").val();
            return $.ajax({
                url: '/ajax/getFormData?form_id=' + form_id,
                async: false,
                type: 'GET',
                cache: false,
                success: function(data) {
                    var body_data = $("body").data();
                    if (data || data != "") {
                        body_data.user_form_json_data = JSON.parse(data);
                        console.log(body_data.user_form_json_data);
                        $("body").data(body_data);
                        console.log("WHAT")
                        console.log($("body").data())
                    }
                }
            }).fail(function() {
                console.log("ERROR AJAX GET_FORM_JSON");
            })
        },
        "setFieldsVisibility": function() {
            $('.getFields').each(function() {
                var visibility = $(this).attr('field-visible');

                switch (visibility) {
                    case "true":
                        $(this).parents('.setOBJ').eq(0).css('display', 'block');
                        break;
                    case "false":
                        $(this).parents('.setOBJ').eq(0).css('display', 'none');
                        break;
                }
            });

        },
        "computeVisibility": function() {
            if (typeof callBack == "undefined") {

            }
            var data = [];
            $('[field-visible="computed"]').each(function(index) {
                if ($(this).attr('visible-formula')) {
                    var fieldName = $(this).attr('name');
                    if (typeof fieldName == "undefined") {
                        fieldName = $(this).attr('tab-name');
                    }
                    var formula = $(this).attr('visible-formula');
                    var process_formula = formula;
                    var getFieldName = formula.match(/@[A-Za-z_][A-Za-z0-9_]*/g);
                    
                    if(getFieldName != null){
                        getFieldName = getFieldName.filter(Boolean);
                        console.log("getFieldName", getFieldName);
                        for (var ctr = 0; ctr < getFieldName.length; ctr++) {
                            console.log("WHOA", $('[name="' + getFieldName[ctr].replace("@", "") + '"]'))
                            if ($('[name="' + getFieldName[ctr].replace("@", "") + '"]').length >= 1) {
                                var type = $('[name="' + getFieldName[ctr].replace("@", "") + '"]').attr('type');
                                if (type == 'radio') {
                                    var value_fn = $('[name="' + getFieldName[ctr].replace("@", "") + '"]:checked').val();
                                } else {
                                    var value_fn = $('[name="' + getFieldName[ctr].replace("@", "") + '"]').val();
                                }
                                process_formula = process_formula.replace(getFieldName[ctr], "'" + value_fn + "'");
                            }
                        }
                        data.push({
                            FieldName: fieldName,
                            Formula: process_formula
                        });
                    }
                    
                }
            });
            // console.log("ETOOO BAAz");
            // console.log(data);
            
            for (var index in data) {
                var returnFieldName = data[index].FieldName;
                console.log(data[index].Formula);
                var returnFieldValue = eval(data[index].Formula);
                var role = "";
                if ($('[tab-name="' + returnFieldName + '"]').attr("role")) {
                    role = $('[tab-name="' + returnFieldName + '"]').attr("role");
                }
                if (role.length >= 1 && role == "tab") {
                    var tab_navigation_ele = $('[tab-name="' + returnFieldName + '"]');
                    var content_id_ele = $('[tab-name="' + returnFieldName + '"]').children("a[role='presentation']").attr("href");
                    if (returnFieldValue) {
                        if (tab_navigation_ele.eq(0).css("display") == "none") {
                            tab_navigation_ele.eq(0).show();
                            $(content_id_ele).show();
                            tab_navigation_ele.eq(0).parents(".form-tabbable-pane").eq(0).css("height", "");
                            // tab_navigation_ele.eq(0).parents(".form-tabbable-pane").eq(0).css("width","");
                            tab_navigation_ele.eq(0).children("a").click();
                        }
                    } else {
                        if (tab_navigation_ele.eq(0).css("display") != "none") {
                            tab_navigation_ele.eq(0).hide();
                            $(content_id_ele).hide();
                            if (tab_navigation_ele.eq(0).next().length >= 1 && tab_navigation_ele.eq(0).next().css("display") != "none") {
                                tab_navigation_ele.eq(0).next().children("a").click();
                            } else if (tab_navigation_ele.eq(0).prev().length >= 1 && tab_navigation_ele.eq(0).prev().css("display") != "none") {
                                tab_navigation_ele.eq(0).prev().children("a").click();
                            } else {
                                console.log("WALA NANG NAKA DISPLAY NA TAB")
                                // width_of_tab_panel = tab_navigation_ele.eq(0).parents(".setOBJ").eq(0).outerWidth();
                                height_of_tab = tab_navigation_ele.eq(0).css("height").replace("px", "");
                                height_of_tab_content = $(tab_navigation_ele.eq(0).children("a").eq(0).attr("href")).css("height").replace("px", "");
                                // console.log(tab_navigation_ele.eq(0).parents(".form-tabbable-pane").eq(0))
                                // console.log(width_of_tab_content+"  "+height_of_tab + "  " + height_of_tab_content)
                                tab_navigation_ele.eq(0).parents(".form-tabbable-pane").eq(0).css("height", (Number(height_of_tab) + Number(height_of_tab_content)) + "px")
                                // tab_navigation_ele.eq(0).parents(".form-tabbable-pane").eq(0).css("width",(width_of_tab_panel)+"px")
                                console.log(tab_navigation_ele.eq(0))
                            }
                        }
                    }
                } else {
                    if (returnFieldValue) {
                        // console.log("COMPUTE SPACES toblock", computeGap($('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0),'expand') );
                        if ($('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).attr("compute-visibility-display")) {
                            $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css("display", $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).attr("compute-visibility-display"));
                        } else {
                            if ($('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css("display") != "none") {
                                $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css('display', $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css('display'));
                            } else {
                                $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css('display', 'block');
                            }
                        }
                    } else {
                        // console.log("COMPUTE SPACES togap", computeGap($('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0),'collapse') );
                        if ($('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css("display") != "none") {
                            $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).attr("compute-visibility-display", $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css("display"));
                        }
                        $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css('display', 'none');

                    }
                }
            }
            checkStaticTablesGAP();
        },
        "populateFormula": function(object, callBack) {
            if (typeof callBack == "undefined") {

            }
            var obj_name = "";
            if (object) {
                obj_name = $(object).attr("name");
            }
            var data = [];
            $('.getFields').each(function(index) {
                if ($(this).attr('default-type') != "computed" || typeof $(this).attr('default-type') === "undefined") {
                    return true;
                }

                if ($(this).attr('default-formula-value')) {
                    var fieldName = $(this).attr('name');
                    var formula = $(this).attr('default-formula-value');
                    var process_formula = formula;
                    var getFieldName = formula.match(/@[A-Za-z_][A-Za-z0-9_]*/g);

                    if (getFieldName) {
                        for (var ctr = 0; ctr < getFieldName.length; ctr++) {
                            if ($('[name="' + getFieldName[ctr].replace("@", "") + '"]').length >= 1) {
                                var value_fn = $('[name="' + getFieldName[ctr].replace("@", "") + '"]').val().replace("@","^@");
                                process_formula = process_formula.replace(getFieldName[ctr], "'" + value_fn + "'");
                            }
                        }
                    }
                    //console.log(process_formula)
                    if (process_formula.match(/^@Total\(.*\)$/) != null || process_formula.indexOf("@Lookup") >= 0 || process_formula.indexOf("@RecordCount") >= 0) {
                        data.push({
                            RequestID: $("#ID").val(),
                            FieldName: fieldName,
                            Formula: process_formula
                        });
                        //console.log("OK SERVER FORMULA")
                    }
                }
            });

            console.log("ajaxFormula", data);
            if (data.length >= 1) {
                $.post('/ajax/ajaxformula', {
                    data: JSON.stringify(data)
                }, function(result) {
                    // $("html").html(result)
                    console.log("TEST CANDY", result)
                    var result = JSON.parse(result);

                    //console.log(result);
                    for (var index in result) {
                        var returnFieldName = result[index].FieldName;
                        var returnFieldValue = result[index].FieldValue;

                        //console.log(returnFieldName);
                        //console.log($('[name="' + returnFieldName + '"]'))
                        $('[name="' + returnFieldName + '"]').val(returnFieldValue);
                        if (obj_name != returnFieldName) {
                            $('[name="' + returnFieldName + '"]').change();
                        }
                    }
                    if (typeof callBack != "undefined") {
                        callBack();
                    }
                });
            }
        },
        "addRefreshEvent": function() {
            var self = this;
            $("body").on("change", '[lookup-event-trigger="true"]', function() {
                self.populateFormula(this);
            });
        },
        "visibilityOnChange":function(){
            var self = this;
            $('[field-visible="computed"][visible-formula]').each(function(){
                var dis_ele = $(this)
                var dis_visible_formula = dis_ele.attr('visible-formula');
                var regeks_get_name = new RegExp("@[a-zA-Z][a-zA-Z0-9_]*","g");
                var names_in_formula = dis_visible_formula.match(regeks_get_name)
                if(names_in_formula != null){
                    names_in_formula = names_in_formula.filter(Boolean);
                }
                var fname_ele = null;
                for(var ii in names_in_formula){
                    fname_ele = $('[name="'+names_in_formula[ii].replace("@","")+'"]');
                    if(fname_ele.length >= 1){
                        self.computeVisibility.call(dis_ele);
                        fname_ele.on("change",function(){
                            var with_formula_ele = dis_ele;
                            self.computeVisibility.call($(this).add(with_formula_ele));
                        });
                    }
                }
            });
        },
        addCommentRequest: function() {
            $("body").on("click", "#reply", function(e) {
                var fID = $(this).attr("data-f-id");
                replyComment(this, fID);
            });
        },
        formatCurrency: function() {
            $('[data-input-type="Currency"]').each(function() {
                var currency = $(this).val();
                var newValue = Number(currency.replace(/[^0-9\.]+/g, ""));
                $(this).val(newValue);
            });
        }
    }





















































    function StrUpper(string_val) {
        if (typeof string_val == "string") {
            return string_val.toUpperCase();
        } else {
            return "StrLower:Not a string";
        }
    }

    function StrLower(string_val) {
        if (typeof string_val == "string") {
            return string_val.toLowerCase();
        } else {
            return "StrLower:Not a string";
        }
    }

    function StrLeft(str_val, str_length) {
        var str_to_process = String(str_val);
        return str_to_process.substr(0, str_length);
    }

    function StrRight(str_val, str_length) {
        var str_to_process = String(str_val);
        var start = (str_to_process.length - (str_length));
        if (start <= -1) {
            start = 0;
        }
        return str_to_process.substr(start, str_length);
    }

    function StrCount(str_val) {
        if (typeof str_val != "undefined") {
            return String(str_val).length;
        }
    }
    // function AdjustDate(type, date, added_value){
    //     if(typeof added_value === "undefined"){
    //         added_value = '';
    //     }
    //     value_add = Number(added_value);
    //     switch (type) {
    //         case 'day':
    //             // $date = date("Y-m-d H:i", strtotime(date("Y-m-d H:i", strtotime($date)) . " ".$value_add." day"));
    //             // Date.prototype.adjustDay = function(value) {
    //             //     if ($.isNumeric(value)) {
    //             //         var new_date = this.setDate(parseInt(this.getDate()) + parseInt(value));
    //             //         var obj_new_date = new Date(new_date);
    //             //         return obj_new_date;
    //             //     } else {
    //             //         return "";
    //             //     }
    //             // }
    //             var new_date = ThisDate(date).setDate(parseInt(ThisDate(date).getDate()) + parseInt(value_add));
    //             var obj_new_date = new Date(new_date);
    //             date = obj_new_date;
    //             break;
    //         case 'month':
    //             // Date.prototype.adjustMonth = function(value) {
    //             //     if ($.isNumeric(value)) {
    //             //         var new_date = this.setMonth(parseInt(this.getMonth()) + parseInt(value));
    //             //         var obj_new_date = new Date(new_date);
    //             //         return obj_new_date;
    //             //     } else {
    //             //         return "";
    //             //     }
    //             // }

    //             // $date = date("Y-m-d H:i", strtotime(date("Y-m-d H:i", strtotime($date)) . " ".$value_add." month"));

    //             var new_date = this.setMonth(parseInt(this.getMonth()) + parseInt(value));
    //             var obj_new_date = new Date(new_date);
    //             break;
    //         case 'year':
    //             $date = date("Y-m-d H:i", strtotime(date("Y-m-d H:i", strtotime($date)) . " ".$value_add." year"));
    //             break;
    //         case 'minute':
    //             $date = date("Y-m-d H:i", strtotime(date("Y-m-d H:i", strtotime($date)) . " ".$value_add." minute"));
    //             break;
    //         case 'hour':
    //             $date = date("Y-m-d H:i", strtotime(date("Y-m-d H:i", strtotime($date)) . " ".$value_add." day"));
    //             break;
    //         case 'week':
    //             $date = date("Y-m-d H:i", strtotime(date("Y-m-d H:i", strtotime($date)) . " ".$value_add." week"));
    //             break;
    //     }
    //     return date;
    // }

    function GetAuth(str_key_entry){
        var key_entries = ["FormAuthID","FormAuthEmail"];
        var get_ele = $('[name="'+str_key_entry+'"]');
        if(key_entries.indexOf(str_key_entry) >= 0){
            if(get_ele.length >= 1){
                return get_ele.val();
            }else{
                return "";
            }
        }else{
            return "";
        }
    }
    function StrConcat() {
        var args = arguments;//infinite argument
        var collect_strings = "";
        for (var ctr = 0; ctr < args.length; ctr++) {
            collect_strings = collect_strings + args[ctr];
        }
        return collect_strings;
    }
    function GetRowIndex(element){
        var dis_ele = $(element);
        var row_index = -1;
        if(dis_ele.hasClass("getFields")){
            row_index = dis_ele.parents(".setOBJ").eq(0).parents("tr").eq(0).index();
        }else{
            row_index = dis_ele.parents("tr").eq(0).index();
        }
        return row_index;
    }
    function StrGet(str_val, str_istart, str_char_len) {
        if (typeof str_val == "undefined") {
            return "";
        }
        var string_val = String(str_val);
        var string_start_index = Number(str_istart);
        if (string_start_index <= 0) {
            return "";
        }
        if (typeof str_char_len == "undefined") {
            return String(string_val.charAt((Number(str_istart) - 1)));
        } else {
            return string_val.substr((Number(str_istart) - 1), Number(str_char_len));
        }
    }

    function printAllExistingFormulas() {
        var collect_in_json = [];
        $('[default-formula-value][default-type="computed"]').each(function() {
            collect_in_json.push({
                "this_ele_formula": $(this).attr("default-formula-value"),
                "this_ele": $(this),
                "object_id": $(this).closest(".setOBJ").attr("data-object-id")
            })
            console.log($(this).attr("default-formula-value"));
        });
        console.log("===========================================");
        console.log("check DOM here below!");
        return collect_in_json;
    }

    function GetRound(given_num, decimal_digit) {
        var decimal_places = "1";
        for (var ii = 1; ii <= decimal_digit; ii++) {
            decimal_places += "" + "0";
        }
        decimal_places = Number(decimal_places);
        return Math.round(given_num * decimal_places) / decimal_places;
    }
    function SDev(fieldname) {
        var fn_str = fieldname;
        var nums = [];
        nums.push(Number($('[name="' + fn_str + '"]').val()))

        $('[rep-original-name="' + fn_str + '"]').each(function() {
            nums.push(Number($(this).val()));
        });

        var dataSD = {};
        var mean = 0;
        var mean_average = 0;
        var decimal = 1000000;

        dataSD.totalNumbers = nums.length;

        function getMean(nums) {
            for (var ii in nums) {
                mean = mean + parseFloat(nums[ii]);
            }
            mean = mean / nums.length;
            mean_average = Math.round(mean * decimal) / decimal;
            return Math.round(mean * decimal) / decimal;
        }
        dataSD.meanAverage = getMean(nums);

        var variance = 0;
        var varian = 0;

        function getVariance(nums) {
            for (var ii in nums) {
                variance = variance + Math.pow((parseFloat(nums[ii]) - mean), 2);
            }
            varian = variance / (nums.length - 1);
            varian = (isNaN(varian) == false) ? varian : 0;
            return Math.round(varian * decimal) / decimal;
        }
        dataSD.varianceSD = getVariance(nums);

        var sd = 0;

        function getStandardDeviation() {
            sd = Math.sqrt(varian);
            return Math.round(sd * decimal) / decimal;
        }
        dataSD.standardDeviation = getStandardDeviation();
        var pop = 0;

        function getPopulationSD(nums) {
            pop = variance / nums.length;
            pop_sqrt = Math.sqrt(pop);
            return Math.round(pop_sqrt * decimal) / decimal;
        }
        dataSD.populationSD = getPopulationSD(nums);

        var var_pop = 0;

        function getVariancePSD(nums) {
            var_pop = variance / nums.length;
            return Math.round(var_pop * decimal) / decimal;
        }
        dataSD.variancePSD = getVariancePSD(nums);
        return dataSD["standardDeviation"];
    }
    function Sum(sum_fn) {
        var fieldname = sum_fn;
        var summation = 0;
        if (fieldname.indexOf("@") >= 0) {
            fieldname = fieldname.replace("@", "");
        }
        summation = summation + Number($('[name="' + fieldname + '"]').val().replace(/,/g, ""));

        $('[rep-original-name="' + fieldname + '"]').each(function(eqi) {
            summation = summation + Number($(this).val().replace(/,/g, ""));
        });

        return summation;
    }
    function GetAVG(fns) {
        var fieldname = "@" + fns;
        var collect_values = [];
        var totality = 0;
        var counted_names = 0;
        console.log('asd', fieldname)
        if (fieldname.indexOf("@") >= 0) {
            fieldname = fieldname.replace("@", "");
            totality = totality + Number($('[name="' + fieldname + '"]').val());
            counted_names++;
            $('[rep-original-name="' + fieldname + '"]').each(function(eqi) {
                totality = totality + Number($(this).val());
                counted_names++;
            });
            if (counted_names == 0) {
                return 0;
            } else {
                return (totality / counted_names);
            }
        } else {

        }
    }
    function GetMax(fns) {
        var fieldname = fns;
        var collect_values = [];
        if (fieldname.indexOf("@") >= 0) {
            fieldname = fieldname.replace("@", "");
        }
        collect_values.push(Number($('[name="' + fieldname + '"]').val()));

        $('[rep-original-name="' + fieldname + '"]').each(function(eqi) {
            collect_values.push(Number($(this).val()));
        });
        if (collect_values.length == 0) {
            return "";
        } else {
            return (collect_values.sort(function(a, b) {
                return b - a
            }))[0];
        }
    }

    function GetMin(fns) {
        var fieldname = fns;
        var collect_values = [];
        if (fieldname.indexOf("@") >= 0) {
            fieldname = fieldname.replace("@", "");
        }
        collect_values.push(Number($('[name="' + fieldname + '"]').val()));

        $('[rep-original-name="' + fieldname + '"]').each(function(eqi) {
            collect_values.push(Number($(this).val()));
        });

        if (collect_values.length == 0) {
            return "";
        } else {
            return (collect_values.sort(function(a, b) {
                return a - b
            }))[0];
        }
    }
    function CountDayIf(start_date, end_date) {
        var args = arguments;
        var starting_date = new Date(start_date);

        var ending_date = new Date(end_date);
        var counted_if_days = 0;

        if (typeof args[2] !== "undefined") {

            var days_difference = ending_date.diffDaysIn(starting_date);
            for (var ii = 0; ii <= days_difference; ii++) {
                if (ii == 0) {
                    var adjusted_day = starting_date.adjustDay(0).formatDate('l');
                } else {
                    var adjusted_day = starting_date.adjustDay(+1).formatDate('l');
                }
                console.log(ii,adjusted_day,starting_date)
                for (var ca = 0; ca < args.length; ca++) {

                    var param_day = args[ca];
                    if ((adjusted_day == param_day && ca >= 2) != false) {

                        // console.log(adjusted_day+" == "+param_day+" && "+ca+" >= "+2+"\n",(( adjusted_day == param_day && ca >= 2 ) != false ))
                        counted_if_days++;
                    }
                }
            }
            return counted_if_days;
        }
    }
    function GetTimeInt(date_here){
        var date_parse = new Date(date_here);
        if(date_parse == "Invalid Date"){
            return date_parse.getTime();
        }else{
            return date_parse.getTime();
        }
    }
    function ThisDate(this_date) {
		var parse_first = new Date(this_date);
		if(parse_first == "Invalid Date"){
			return parse_first;
		}
        var this_time = parse_first.toString().match(/..:..:..\s[AMP]{2}|..:..\s[AMP]{2}|..:..:..|..:../g);
        if (this_time != null) {
            var this_time2 = this_time[0].replace(/\s[A-Za-z]{2}/g, "");
            var this_time_splitted = this_time2.split(":");
            var time_hours = "";
            var time_minutes = "";
            var time_seconds = "";
            if (typeof this_time_splitted[0] != "undefined") { //hours
                time_hours = this_time_splitted[0];
            }
            if (typeof this_time_splitted[1] != "undefined") { //minutes
                time_minutes = this_time_splitted[1];
            }
            var dis_date = parse_first.toString().replace(this_time[0], "");
			
			//console.log("TARGET taas",$.trim(dis_date))
            var this_new_date = new Date($.trim(dis_date));

            this_new_date = new Date(this_new_date.setHours(time_hours));

            this_new_date = new Date(this_new_date.setMinutes(time_minutes));
        } else {
			//console.log("TARGET baba",this_date)
            var this_new_date = new Date(this_date);
        }


        // var converted_date = (this_new_date.getFullYear())+"-"+(this_new_date.getMonth()+1)+"-"+(this_new_date.getDate());
        if (this_new_date == "Invalid Date") {
            return this_new_date;
        } else {
            return this_new_date;
        }
    }
    Number.prototype.currencyFormat = function() {
        // (?<=\d)(?=(\d\d\d)+(?!\d))
        // return this.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
        // console.log(this)
        // console.log("ow")
        var check_expo = this.toString();
        var reg_eks_expo = new RegExp("e\\+\\d", "g");
        var matched_expo = check_expo.match(reg_eks_expo);
        // console.log("CURRENCY FORMAT",matched_expo)
        if (matched_expo == null) {
            var negative_pad = "";
            var float_value = "";
            var integer = "";
            if (this < 0) {
                negative_pad = "-";
                float_value = this.toString().split(".");
                integer = float_value[0].replace("-", "");
            } else {
                float_value = this.toString().split(".");
                integer = float_value[0];
            }

            var decimal = "";
            if (float_value.length == 2) {
                decimal = float_value[1];
                integer = negative_pad + integer.split(/(?=(?:...)*$)/).join(",");
                return integer + "." + decimal;
            } else {
                integer = negative_pad + integer.split(/(?=(?:...)*$)/).join(",");
                return integer + ".00";
            }
        } else {
            return this;
        }
    };
    Date.prototype.formatDate = function(format) {
        if (this == "Invalid Date") {
            return this;
        } else {
            timestamp = this;
            // http://kevin.vanzonneveld.net
            // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
            // +      parts by: Peter-Paul Koch (http://www.quirksmode.org/js/beat.html)
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: MeEtc (http://yass.meetcweb.com)
            // +   improved by: Brad Touesnard
            // +   improved by: Tim Wiel
            // +   improved by: Bryan Elliott
            // +   improved by: David Randall
            // +      input by: Brett Zamir (http://brett-zamir.me)
            // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: Theriault
            // +  derived from: gettimeofday
            // +      input by: majak
            // +   bugfixed by: majak
            // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +      input by: Alex
            // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
            // +   improved by: Theriault
            // +   improved by: Brett Zamir (http://brett-zamir.me)
            // +   improved by: Theriault
            // +   improved by: Thomas Beaucourt (http://www.webapp.fr)
            // +   improved by: JT
            // +   improved by: Theriault
            // +   improved by: Rafał Kukawski (http://blog.kukawski.pl)
            // +   bugfixed by: omid (http://phpjs.org/functions/380:380#comment_137122)
            // +      input by: Martin
            // +      input by: Alex Wilson
            // +      input by: Haravikk
            // +   improved by: Theriault
            // +   bugfixed by: Chris (http://www.devotis.nl/)
            // %        note 1: Uses global: php_js to store the default timezone
            // %        note 2: Although the function potentially allows timezone info (see notes), it currently does not set
            // %        note 2: per a timezone specified by date_default_timezone_set(). Implementers might use
            // %        note 2: this.php_js.currentTimezoneOffset and this.php_js.currentTimezoneDST set by that function
            // %        note 2: in order to adjust the dates in this function (or our other date functions!) accordingly
            // *     example 1: date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h',  );
            // *     returns 1: '09:09:40 m is month'
            // *     example 2: date('F j, Y, g:i a', 1062462400);
            // *     returns 2: 'September 2, 2003, 2:26 am'
            // *     example 3: date('Y W o', 1062462400);
            // *     returns 3: '2003 36 2003'
            // *     example 4: x = date('Y m d', (new Date()).getTime()/1000);
            // *     example 4: (x+'').length == 10 // 2009 01 09
            // *     returns 4: true
            // *     example 5: date('W', 1104534000);
            // *     returns 5: '53'
            // *     example 6: date('B t', 1104534000);
            // *     returns 6: '999 31'
            // *     example 7: date('W U', 1293750000.82); // 2010-12-31
            // *     returns 7: '52 1293750000'
            // *     example 8: date('W', 1293836400); // 2011-01-01
            // *     returns 8: '52'
            // *     example 9: date('W Y-m-d', 1293974054); // 2011-01-02
            // *     returns 9: '52 2011-01-02'
            var that = this,
                    jsdate,
                    f,
                    // Keep this here (works, but for code commented-out
                    // below for file size reasons)
                    //, tal= [],
                    txt_words = ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                    // trailing backslash -> (dropped)
                    // a backslash followed by any character (including backslash) -> the character
                    // empty string -> empty string
                    formatChr = /\\?(.?)/gi,
                    formatChrCb = function(t, s) {
                        return f[t] ? f[t]() : s;
                    },
                    _pad = function(n, c) {
                        n = String(n);
                        while (n.length < c) {
                            n = '0' + n;
                        }
                        return n;
                    };
            f = {
                // Day
                d: function() { // Day of month w/leading 0; 01..31
                    return _pad(f.j(), 2);
                },
                D: function() { // Shorthand day name; Mon...Sun
                    return f.l().slice(0, 3);
                },
                j: function() { // Day of month; 1..31
                    return jsdate.getDate();
                },
                l: function() { // Full day name; Monday...Sunday
                    return txt_words[f.w()] + 'day';
                },
                N: function() { // ISO-8601 day of week; 1[Mon]..7[Sun]
                    return f.w() || 7;
                },
                S: function() { // Ordinal suffix for day of month; st, nd, rd, th
                    var j = f.j(),
                            i = j % 10;
                    if (i <= 3 && parseInt((j % 100) / 10, 10) == 1) {
                        i = 0;
                    }
                    return ['st', 'nd', 'rd'][i - 1] || 'th';
                },
                w: function() { // Day of week; 0[Sun]..6[Sat]
                    return jsdate.getDay();
                },
                z: function() { // Day of year; 0..365
                    var a = new Date(f.Y(), f.n() - 1, f.j()),
                            b = new Date(f.Y(), 0, 1);
                    return Math.round((a - b) / 864e5);
                },
                // Week
                W: function() { // ISO-8601 week number
                    var a = new Date(f.Y(), f.n() - 1, f.j() - f.N() + 3),
                            b = new Date(a.getFullYear(), 0, 4);
                    return _pad(1 + Math.round((a - b) / 864e5 / 7), 2);
                },
                // Month
                F: function() { // Full month name; January...December
                    return txt_words[6 + f.n()];
                },
                m: function() { // Month w/leading 0; 01...12
                    return _pad(f.n(), 2);
                },
                M: function() { // Shorthand month name; Jan...Dec
                    return f.F().slice(0, 3);
                },
                n: function() { // Month; 1...12
                    return jsdate.getMonth() + 1;
                },
                t: function() { // Days in month; 28...31
                    return (new Date(f.Y(), f.n(), 0)).getDate();
                },
                // Year
                L: function() { // Is leap year?; 0 or 1
                    var j = f.Y();
                    return j % 4 === 0 & j % 100 !== 0 | j % 400 === 0;
                },
                o: function() { // ISO-8601 year
                    var n = f.n(),
                            W = f.W(),
                            Y = f.Y();
                    return Y + (n === 12 && W < 9 ? 1 : n === 1 && W > 9 ? -1 : 0);
                },
                Y: function() { // Full year; e.g. 1980...2010
                    return jsdate.getFullYear();
                },
                y: function() { // Last two digits of year; 00...99
                    return f.Y().toString().slice(-2);
                },
                // Time
                a: function() { // am or pm
                    return jsdate.getHours() > 11 ? "pm" : "am";
                },
                A: function() { // AM or PM
                    return f.a().toUpperCase();
                },
                B: function() { // Swatch Internet time; 000..999
                    var H = jsdate.getUTCHours() * 36e2,
                            // Hours
                            i = jsdate.getUTCMinutes() * 60,
                            // Minutes
                            s = jsdate.getUTCSeconds(); // Seconds
                    return _pad(Math.floor((H + i + s + 36e2) / 86.4) % 1e3, 3);
                },
                g: function() { // 12-Hours; 1..12
                    return f.G() % 12 || 12;
                },
                G: function() { // 24-Hours; 0..23
                    return jsdate.getHours();
                },
                h: function() { // 12-Hours w/leading 0; 01..12
                    return _pad(f.g(), 2);
                },
                H: function() { // 24-Hours w/leading 0; 00..23
                    return _pad(f.G(), 2);
                },
                i: function() { // Minutes w/leading 0; 00..59
                    return _pad(jsdate.getMinutes(), 2);
                },
                s: function() { // Seconds w/leading 0; 00..59
                    return _pad(jsdate.getSeconds(), 2);
                },
                u: function() { // Microseconds; 000000-999000
                    return _pad(jsdate.getMilliseconds() * 1000, 6);
                },
                // Timezone
                e: function() { // Timezone identifier; e.g. Atlantic/Azores, ...
                    // The following works, but requires inclusion of the very large
                    // timezone_abbreviations_list() function.

                    throw 'Not supported (see source code of date() for timezone on how to add support)';
                },
                I: function() { // DST observed?; 0 or 1
                    // Compares Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC.
                    // If they are not equal, then DST is observed.
                    var a = new Date(f.Y(), 0),
                            // Jan 1
                            c = Date.UTC(f.Y(), 0),
                            // Jan 1 UTC
                            b = new Date(f.Y(), 6),
                            // Jul 1
                            d = Date.UTC(f.Y(), 6); // Jul 1 UTC
                    return ((a - c) !== (b - d)) ? 1 : 0;
                },
                O: function() { // Difference to GMT in hour format; e.g. +0200
                    var tzo = jsdate.getTimezoneOffset(),
                            a = Math.abs(tzo);
                    return (tzo > 0 ? "-" : "+") + _pad(Math.floor(a / 60) * 100 + a % 60, 4);
                },
                P: function() { // Difference to GMT w/colon; e.g. +02:00
                    var O = f.O();
                    return (O.substr(0, 3) + ":" + O.substr(3, 2));
                },
                T: function() { // Timezone abbreviation; e.g. EST, MDT, ...
                    // The following works, but requires inclusion of the very
                    // large timezone_abbreviations_list() function.

                    return 'UTC';
                },
                Z: function() { // Timezone offset in seconds (-43200...50400)
                    return -jsdate.getTimezoneOffset() * 60;
                },
                // Full Date/Time
                c: function() { // ISO-8601 date.
                    return 'Y-m-d\\TH:i:sP'.replace(formatChr, formatChrCb);
                },
                r: function() { // RFC 2822
                    return 'D, d M Y H:i:s O'.replace(formatChr, formatChrCb);
                },
                U: function() { // Seconds since UNIX epoch
                    return jsdate / 1000 | 0;
                }
            };
            this.date = function(format, timestamp) {
                that = this;
                jsdate = (timestamp === undefined ? new Date() : // Not provided
                        (timestamp instanceof Date) ? new Date(timestamp) : // JS Date()
                        new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int)
                        );
                return format.replace(formatChr, formatChrCb);
            };
            return this.date(format, timestamp);
        }//end of if
    }
    Date.prototype.diffHoursIn = function(date2) {
        // / 1000 / 60 / 60
        if (typeof date2 != "undefined" && this != "Invalid Date") {
            var date2_dt_obj = new Date(date2);
            var t2 = date2_dt_obj.getTime();
            var t1 = this.getTime();
            return /*Math.abs*/((t1 - t2) / 1000 / 60 / 60);
        } else {
            return "";
        }
    }
    Date.prototype.diffDaysIn = function(date2) {
        if (typeof date2 != "undefined" && this != "Invalid Date") {
            var date2_dt_obj = new Date(date2);
            var t2 = date2_dt_obj.getTime();
            var t1 = this.getTime();
            return /*Math.abs*/(parseInt((t1 - t2) / (24 * 3600 * 1000), 10));
        } else {
            return "";
        }
    }
    Date.prototype.diffWeeksIn = function(date2) {
        if (typeof date2 != "undefined" && date2.length >= 1 && this != "Invalid Date") {
            var date2_dt_obj = new Date(date2);
            var t2 = date2_dt_obj.getTime();
            var t1 = this.getTime();

            return /*Math.abs*/(parseInt((t1 - t2) / (24 * 3600 * 1000 * 7)));
        } else {
            return "";
        }
    }
    Date.prototype.diffMonthsIn = function(date2) {
        if (typeof date2 != "undefined" && date2.length >= 1 && this != "Invalid Date") {
            var date2_dt_obj = new Date(date2);
            var d1Y = this.getFullYear();
            var d2Y = date2_dt_obj.getFullYear();
            var d1M = this.getMonth();
            var d2M = date2_dt_obj.getMonth();
            return /*Math.abs*/((d1M + 12 * d1Y) - (d2M + 12 * d2Y));
        } else {
            return "";
        }
    }

    Date.prototype.diffYearsIn = function(date2) {
        if (typeof date2 != "undefined" && date2.length >= 1 && this != "Invalid Date") {
            var date2_dt_obj = new Date(date2);
            return /*Math.abs*/(date2_dt_obj.getFullYear() - this.getFullYear());
        } else {
            return "";
        }
    }

    Date.prototype.adjustSeconds = function(value) {
        if ($.isNumeric(value)) {
            var new_date = this.setSeconds(parseInt(this.getSeconds()) + parseInt(value));
            var obj_new_date = new Date(new_date);
            return obj_new_date;
        } else {
            return "";
        }
    }
    Date.prototype.adjustMinutes = function(value) {
        if ($.isNumeric(value)) {
            var new_date = this.setMinutes(parseInt(this.getMinutes()) + parseInt(value));
            var obj_new_date = new Date(new_date);
            return obj_new_date;
        } else {
            return "";
        }
    }
    Date.prototype.adjustHours = function(value) {
        if ($.isNumeric(value)) {
            var new_date = this.setHours(parseInt(this.getHours()) + parseInt(value));
            var obj_new_date = new Date(new_date);
            return obj_new_date;
        } else {
            return "";
        }
    }
    Date.prototype.adjustDay = function(value) {
        if ($.isNumeric(value)) {
            var new_date = this.setDate(parseInt(this.getDate()) + parseInt(value));
            var obj_new_date = new Date(new_date);
            return obj_new_date;
        } else {
            return "";
        }
    }
    Date.prototype.adjustMonth = function(value) {
        if ($.isNumeric(value)) {
            var new_date = this.setMonth(parseInt(this.getMonth()) + parseInt(value));
            var obj_new_date = new Date(new_date);
            return obj_new_date;
        } else {
            return "";
        }
    }
    Date.prototype.adjustYear = function(value) {
        if ($.isNumeric(value)) {
            var new_date = this.setFullYear(parseInt(this.getFullYear()) + parseInt(value));
            var obj_new_date = new Date(new_date);
            return obj_new_date;
        } else {
            return "";
        }
    }
    function sortMyObjectByKey(arrayObject, keyNameValToSort) {
        var myArrayOfObj = arrayObject;
        // myArrayOfObj.sort(function (a, b) {
        //     if (a[keyNameValToSort] < b[keyNameValToSort]) {
        //         return -1;
        //     }
        //     else if (a[keyNameValToSort] > b[keyNameValToSort]) {
        //         return 1;
        //     }
        //     return 0;
        // });
        // return myArrayOfObj;
        return myArrayOfObj.sort(function(x, y) {
            return x[keyNameValToSort] - y[keyNameValToSort]
        });
    }
    function fieldExists(FIELDNAME) {
        var bool_checker = false;
        try {
            var replaced_str = FIELDNAME.replace(/@/g, "")
            var FN_OBJ = $("[name=" + replaced_str + "]");
            if (FN_OBJ.length >= 1) {
                bool_checker = true;
            } else {
                bool_checker = false;
            }
        } catch (error) {
            console.log("NAG ERROR SA FIELDEXISTS", replaced_str, error)
            bool_checker = false;
        }
        return bool_checker;
    }

    function NumToWord(num) {

        function ConvertHere(s) {
            s = s.replace(/[\, ]/g, '');
            var reg_exp_dec = new RegExp('\\+\\d*', 'g');
            var str_e_digit = s.match(reg_exp_dec);
            var e_digit = 0;
            if (str_e_digit != null) {
                str_e_digit = str_e_digit.filter(Boolean);
                e_digit = Number(str_e_digit[0]);
            }
            // console.log("CONVERT DIGITS",e_digit,str_e_digit, typeof str_e_digit);

            if (s != parseFloat(s))
                return 'not a number';

            var x = s.indexOf('.');
            if (x == -1)
                x = s.length;
            if (x > 20 || e_digit > 20)
                return 'too big';
            var n = s.split('');
            var str = '';
            var sk = 0;

            for (var i = 0; i < x; i++) {

                if ((x - i) % 3 == 2) {

                    if (n[i] == '1') {

                        str += tn[Number(n[i + 1])] + ' ';
                        i++;
                        sk = 1;
                    } else if (n[i] != 0) {
                        str += tw[n[i] - 2] + ' ';
                        sk = 1;
                    }
                } else if (n[i] != 0) {

                    str += dg[n[i]] + ' ';

                    if ((x - i) % 3 == 0)
                        str += 'hundred ';

                    sk = 1;
                }

                if ((x - i) % 3 == 1) {
                    if (sk)
                        str += th[(x - i - 1) / 3] + ' ';
                    sk = 0;
                }
            }
            if (x != s.length) {
                var y = s.length;
                str += 'and ';
                for (var i = x + 1; i < y; i++)
                    str += dg[n[i]] + ' ';
            }
            return str.replace(/\s+/g, ' ');
        }
        if(typeof num !== "undefined" || num != null || num != ""){
            if (typeof num === 'string') {
                var with_comma = num.match(/[\,]/g);
                if(with_comma != null){
                    with_comma = with_comma.filter(Boolean);
                    if (with_comma) {
                        if (with_comma.length >= 1) {
                            num = num.replace(/[\,]/g, "");
                        }
                    }
                }
            }
        }
        if (!isNaN(Number(num))) {
            var s = parseFloat(num).toString();
            // Convert numbers to words
            // copyright 25th July 2006, by Stephen Chapman http://javascript.about.com
            // permission to use this Javascript on your web page is granted
            // provided that all of the code (including this copyright notice) is
            // used exactly as shown (you can change the numbering system if you wish)

            // American Numbering System
            var th = ['', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion'];
            // uncomment this line for English Number System
            // var th = ['','thousand','million','milliard','billion'];

            var dg = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
            var tn = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
            var tw = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];

            var dw = ['tenths', 'hundredths', 'thousandths', 'ten-thousandths', 'hundred-thousandths', 'millionths', 'ten-millionths', 'hundred-millionths', 'billionths', 'ten-billionths', 'hundred-billionths', 'trillionths', 'ten-trillionths', 'hundred-trillionths', 'quadrillionths', 'ten-quadrillionths', 'hundred-quadrillionths'];

            var w_point = s.match(/\./g);
            if (w_point != null && typeof w_point !== "undefined") {
                w_point = w_point.filter(Boolean);

                if (w_point.length == 1) {
                    var w_point_s = s.split(/\./);
                    var collect_s = "";
                    s = w_point_s[0];
                    collect_s += ConvertHere(s);
                    collect_s += "and ";
                    s = w_point_s[1];
                    collect_s += ConvertHere(s);
                    if (typeof dw[s.length - 1] !== "undefined") {
                        collect_s += " " + dw[s.length - 1];
                    }
                    return collect_s;
                } else if (w_point.length >= 2) {
                    return 'Invalid number!';
                } else {

                    //dito na ung my fifthy
                    return ConvertHere(s);
                }
            } else {
                return ConvertHere(s);
            }
        } else {
            return 'Not a number!';
        }
    }






































































    //PROGRESS BAR ADDITIONALS
    var loading_progress_added = -1;

    //LOADING TOOLS/UTILS
    window.setVariableInterval = function(callbackFunc, timing) {
        var variableInterval = {
            interval: timing,
            callback: callbackFunc,
            stopped: false,
            runLoop: function() {
                if (variableInterval.stopped)
                    return;

                var result = variableInterval.callback.call(variableInterval);
                if (typeof result == 'number') {
                    if (result === 0)
                        return;

                    variableInterval.interval = result;
                }
                variableInterval.loop();
            },
            stop: function() {
                this.stopped = true;
                window.clearTimeout(this.timeout);
            },
            start: function() {
                this.stopped = false;
                return this.loop();
            },
            loop: function() {
                this.timeout = window.setTimeout(this.runLoop, this.interval);
                return this;
            }
        };

        return variableInterval;
    };
    function getPercent(containerPx, fillerPx) {
        return (fillerPx / containerPx) * 100;
    }
    function getPX(containerPx, fillerPercent) {
        return (containerPx * fillerPercent) / 100;
    }
    //TEXT VALUES UTILS
    $.fn.selectRange = function(start, end) {
        return this.each(function() {
            if (this.setSelectionRange) {
                this.focus();
                this.setSelectionRange(start, end);
            } else if (this.createTextRange) {
                var range = this.createTextRange();
                range.collapse(true);
                range.moveEnd('character', end);
                range.moveStart('character', start);
                range.select();
            }
        });
    };
    // function getContentEditableVal(contentEditEle){
    //     var ce_elem = $(contentEditEle);
    //     var ce = $("<pre />").html(ce_elem.html());

    //     if($.browser.webkit){
    //            // ce.find("div").each(function(eq){
    //           //   ce.find("div").eq(eq)
    //           // })
    //         ce.find("div").find("br").filter(function(index){
    //             if(index == 0){
    //                 return false;
    //             }else{
    //                 return true;
    //             }
    //         }).replaceWith(function() { return "\n" + this.innerHTML; })
    //         ce.find("div").replaceWith(function() { return "\n" + this.innerHTML; })

    //     }
    //     if($.browser.msie)
    //       ce.find("p").replaceWith(function() { return this.innerHTML  +  "<br>"; });
    //     if($.browser.mozilla || $.browser.opera ||$.browser.msie )
    //       ce.find("br").replaceWith("\n");

    //     var textWithWhiteSpaceIntact = ce.text();
    //     return textWithWhiteSpaceIntact;
    // }
    function getCaretPosition(editableDiv) {

        var element = editableDiv;
        var caretOffset = 0;
        if (typeof window.getSelection != "undefined") {
            var range = window.getSelection().getRangeAt(0);
            var preCaretRange = range.cloneRange();
            preCaretRange.selectNodeContents(element);
            preCaretRange.setEnd(range.endContainer, range.endOffset);
            caretOffset = preCaretRange.toString().length;
        } else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
            var textRange = document.selection.createRange();
            var preCaretTextRange = document.body.createTextRange();
            preCaretTextRange.moveToElementText(element);
            preCaretTextRange.setEndPoint("EndToEnd", textRange);
            caretOffset = preCaretTextRange.text.length;
        }
        // var newLineIndexes = getListREIndexOf($(element), "<div");
        // var sPoint = selection_index["startPoint"];
        // var ePoint = selection_index["endPoint"];
        // for(var iiz in newLineIndexes){
        //     if(newLineIndexes[iiz] > ){
        //         newLineIndexes[iiz];
        //     }
        // }

        // if(typeof range["startOffset"] !== 'undefined'){
        //     if(range["startOffset"] >= 0){
        //         var value_typed = getContentEditableVal($(element));

        //         var index_newline = value_typed.indexOf("\n");
        //         console.log(value_typed,index_newline)
        //         var last_catch = -1;
        //         while(index_newline > 0){

        //             console.log(index_newline, caretOffset)
        //             if(value_typed.indexOf("\n",index_newline + 1) > 0){
        //                 if(value_typed.indexOf("\n",index_newline + 1) > caretOffset && index_newline < caretOffset){
        //                     break;
        //                 }
        //             }else{
        //                 // if(index_newline > caretOffset){
        //                 //     break;
        //                 // }
        //             }

        //             if(value_typed.indexOf("\n",index_newline + 1) < 0){
        //                 last_catch = index_newline;
        //             }
        //             index_newline = value_typed.indexOf("\n",index_newline + 1) ;
        //         }
        //         index_newline = last_catch;

        //     }
        // }
        // index_newline = index_newline -1;
        // if(index_newline < 0){
        //     index_newline = 0;
        // }
        console.log($(element).caret().start, $(element).caret().end)
        return {
            // "index_newline":index_newline,
            "inlineStartPoint": range["startOffset"],
            "startPoint": range["startOffset"],
            "endPoint": caretOffset
        };
    }
    String.prototype.insertReplaceAt = function(start_index, len, str) {
        if (typeof start_index === "number") {
            // console.log(this, "IRA", start_index, len, str, "-===-", this.substr(0, start_index) + str + this.substr(start_index + (len), this.length));
            // console.log("DETAIL", this.substr(0, start_index), "+", str, "+", this.substr(start_index + (len), this.length))
            return this.substr(0, start_index) + str + this.substr(start_index + (len), this.length);
        }
    }
    String.prototype.regexIndexOf = function(regex, startpos) {
        var indexOf = this.substring(startpos || 0).search(regex);
        return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
    }

    String.prototype.regexLastIndexOf = function(regex, startpos) {
        regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
        if (typeof (startpos) == "undefined") {
            startpos = this.length;
        } else if (startpos < 0) {
            startpos = 0;
        }
        var stringToWorkWith = this.substring(0, startpos + 1);
        var lastIndexOf = -1;
        var nextStop = 0;
        while ((result = regex.exec(stringToWorkWith)) != null) {
            lastIndexOf = result.index;
            regex.lastIndex = ++nextStop;
        }
        return lastIndexOf;
    }
    function getListREIndexOf(str, pattern) {
        var collect_indexOf = [];
        i = str.regexIndexOf(new RegExp(pattern, ""));
        collect_indexOf.push(i);
        while (i >= 0) {
            // console.log(i)
            collect_indexOf.push(i);
            i = str.regexIndexOf(new RegExp(pattern, ""), i + 1);
        }
    }
}













{
    //MAKE AN INDEX TOO ON FORMULAS
    // if($(this).attr("default-type")){
    //    if($(this).attr("default-type") == "computed"){
    //      var computed_default_value = $(this).attr("default-formula-value");
    //      var splitted_default_val = computed_default_value.match(/@\(.*?\)|@[a-zA-Z0-9_]*/g);
    //      if(splitted_default_val != null){
    //            console.log("FIGURE THIS OUT")
    //            for(var ctr = 0 ; ctr < splitted_default_val.length ; ctr++){
    //                  var formula_key_words = new Array("@Department","@Status","@Requestor","@RequestID","@Now","@Today","@TrackNo","@CurrentUser","@StrRight","@StrLeft","@GivenIf");
    //                  var ele_in_formula = $('[name="'+splitted_default_val[ctr].replace("@","")+'"]');
    //                  if(ele_in_formula.length >= 1){
    //                        console.log(ele_in_formula.data("events"));
    //                        var ele_in_f_val = $.trim(ele_in_formula.val() );
    //                        if($.isNumeric(ele_in_f_val ) ){
    //                             computed_default_value = computed_default_value.replace(splitted_default_val[ctr], ele_in_f_val);
    //                        }else{
    //                             computed_default_value = computed_default_value.replace(splitted_default_val[ctr], "\""+ele_in_f_val+"\"");
    //                        }
    //                  }else{
    //                         if(formula_key_words.indexOf(splitted_default_val[ctr]) >= 0 ){
    //                            if(splitted_default_val[ctr] == "@Requestor"){
    //                                 requestor_ele = "<?php echo $auth['display_name']; ?>";
    //                                 computed_default_value = computed_default_value.replace(splitted_default_val[ctr],"\""+requestor_ele+"\"" );
    //                            }else if(splitted_default_val[ctr] == "@RequestID"){
    //                                 var value_reqID = $("#ID").val();
    //                                 computed_default_value = computed_default_value.replace(splitted_default_val[ctr], value_reqID);
    //                            }else if(splitted_default_val[ctr] == "@Department"){
    //                                 var value_reqID = $("[name='Department_Name']").val();
    //                                 computed_default_value = computed_default_value.replace(splitted_default_val[ctr], value_reqID);
    //                            }else if(splitted_default_val[ctr] == "@RowIndex"){

    //                                 if($(this).parents("tr").length >=1){
    //                                     var rowIndex_val = $(this).parents("tr").eq(0).index();
    //                                     computed_default_value = computed_default_value.replace(splitted_default_val[ctr], rowIndex_val);
    //                                 }
    //                            }
    //                            continue;
    //                          }else{
    //                            var toBeReplace = splitted_default_val[ctr];
    //                            var formula_RegExp = new RegExp("("+toBeReplace+"|"+toBeReplace+"_tr[0-9]*)","g");
    //                            computed_default_value = computed_default_value.replace(formula_RegExp, splitted_default_val[ctr].replace(/_tr[0-9]*/g,"")+"_tr"+eqi_tr_i);
    //                          }
    //                  }
    //            }
    //      }
    //      var status_ok = "false";
    //      try{
    //         eval(computed_default_value);
    //         status_ok = "true";
    //      }catch(eerr){

    //      }
    //      if(status_ok== "true"){
    //         $(this).val(eval(computed_default_value));
    //      }
    //    }
    // }
    AutoCompletePicklist = {
        "init": function() {
            $('.pickListButton').each(function() {
                var formId = $(this).attr('form-id');
                var returnFieldName = $(this).attr('return-field-name');
                var self = $(this);
                var condition = $(this).attr('condition');
                var returnData = [];
                var picklist_data = {
                    formId: formId,
                    search: '',
                    condition: condition
                };
                picklist.getRequests(picklist_data, function(data) {
                    // self.closest('.setOBJ[data-type="pickList"]').find('.getFields').data("request",data);
                    for (var i in data) {
                        returnData.push(data[i]['' + returnFieldName + ''])
                    }
                    self.closest('.setOBJ[data-type="pickList"]').find(".getFields").autocomplete({
                        source: returnData,
                        select: function(event, ui) {
                            // console.log(ui,event);
                            $(this).val(ui.item.value);
                            $(this).change();
                            return true;
                        },
                        close: function(event, ui) {
                            event.preventDefault();
                            return false;
                        }
                    });
                })
            })
        }
    }
}



{
    // "makeRepeaterTable": function(tableElement, callBack) {
    //     var self_ini = this;
    //     try {
    //         if (typeof callBack == "undefined") {
    //             //do nothing just catch errs
    //         }
    //     } catch (errs) {
    //         console.log(errs)
    //     }

    //     var repeat_fields = ".setObject";
    //     var table_body = $(tableElement).children("tbody");
    //     var table_row = table_body.children("tr");
    //     //MAG LALAGAY MUNA NG BUTTON ADDING SA BAWAT ROW
    //     //at initial startup
    //     //adding buttons
    //     table_row.each(function(eqi_tr) {
    //         td_ele = $(this).children("td");
    //         // relative_content = td_ele.last()/*.eq(0)*/.children(".td-relative");
    //         relative_content = td_ele.eq(0).children(".td-relative");
    //         $(this).addClass("original-row"); //declaring original row
    //         $(this).children("td").attr("row-height", $(this).outerHeight());
    //         relative_content.append(adding_and_removing_btn = $(
    //                 '<span class="repeater-action" style="opacity:0;z-index:2;position:absolute;bottom:0px;">' +
    //                 '<a class="fa fa-plus rep-add-spec-row" style="width:20px;height:20px;padding:5px;"></a>' +
    //                 '<a class="fa fa-minus rep-remove-spec-row" style="width:20px;height:20px;padding:5px;"></a>' +
    //                 '</span>'
    //                 ));
    //         //don't display remove row on original buttons
    //         adding_and_removing_btn.children(".rep-remove-spec-row").eq(0).css({
    //             "display": "none"
    //         });
    //         // adding_and_removing_btn.css({
    //         //    // "margin-left":"-"+(adding_and_removing_btn.css("width")),
    //         //    "margin-right":"-"+(adding_and_removing_btn.css("width")),
    //         //    "position":"absolute",
    //         //    "right":"0px"
    //         // });
    //         adding_and_removing_btn.css({
    //             // "margin-left":"-"+(adding_and_removing_btn.css("width")),
    //             "left": "0px"
    //         });
    //         adding_and_removing_btn.children(".rep-add-spec-row, .rep-remove-spec-row").css({
    //             "width": "auto",
    //             "height": "auto",
    //             "padding": "0px",
    //             "margin": "auto 5px"
    //         });
    //         //adding events for button
    //         evRepeaterAdd(adding_and_removing_btn);
    //         evRepeaterRemove(adding_and_removing_btn);

    //         //adding events for button version 2
    //         // evRepeaterAddV2(adding_and_removing_btn);
    //         // evRepeaterRemoveV2(adding_and_removing_btn);
    //     });

    //     //functionality event
    //     {//OLD VERSION SLOW
    //         function evRepeaterAdd(repeaterBtnEle) {
    //             if (repeaterBtnEle.children(".rep-add-spec-row").length >= 1) {
    //                 repeaterBtnEle.children(".rep-add-spec-row").on({
    //                     "click": function(e) {
    //                         var select_dis_table = $(this).parents("table.form-table");
    //                         if(select_dis_table.data("added_rows_uid")){
    //                             select_dis_table.data("added_rows_uid",(select_dis_table.data("added_rows_uid")+1) );
    //                         }else{
    //                             select_dis_table.data("added_rows_uid",1);
    //                         }
    //                         e.preventDefault();
    //                         var pathname = window.location;

    //                         if ($(this).closest("tr.original-row").length >= 1) {
    //                             //repeat clicked row, append content
    //                             var appended_row = "";
    //                             $(this).closest("tr.original-row").after(appended_row = $(
    //                                 '<tr>' +
    //                                     $(this).closest("tr.original-row").html() +
    //                                 '</tr>'
    //                             ));
    //                             appended_row.children("td").slideUp(500).stop(true, true);
    //                             appended_row.children("td").slideDown(500);
    //                             var rep_btn_container_ar = appended_row.children("td").children(".td-relative").children(".repeater-action");
    //                             //display the remove row button of the repeated row
    //                             rep_btn_container_ar.children(".rep-remove-spec-row").css({
    //                                 "display": ""
    //                             });
    //                             rep_btn_container_ar.css({
    //                                 "left": "0px"
    //                             });
    //                             rep_btn_container_ar.children(".rep-add-spec-row, .rep-remove-spec-row").css({
    //                                 "width": "auto",
    //                                 "height": "auto",
    //                                 "padding": "0px",
    //                                 "margin": "auto 5px"
    //                             });
    //                             //adding event for original row button

    //                             evRepeaterAdd(rep_btn_container_ar);
    //                             evRepeaterRemove(rep_btn_container_ar);
    //                             // rebindFieldFunctionality(appended_row);
    //                             rebindFieldFunctionalityV3(appended_row);
    //                         } else {
    //                             //repeat clicked row, append content
    //                             var appended_row = "";
    //                             $(this).closest("tr").after(appended_row = $(
    //                                 '<tr>' +
    //                                     $(this).closest("tr").html() +
    //                                 '</tr>'
    //                             ));
    //                             appended_row.children("td").slideUp(500).stop(true, true);
    //                             appended_row.children("td").slideDown(500);
    //                             var rep_btn_container_ar2 = appended_row.children("td").children(".td-relative").children(".repeater-action");
    //                             //display the remove row button of the repeated row
    //                             rep_btn_container_ar2.children(".rep-remove-spec-row").css({
    //                                 "display": ""
    //                             });
    //                             rep_btn_container_ar2.css({
    //                                 // "margin-left":"-"+(rep_btn_container_ar2.css("width")),
    //                                 "left": "0px"
    //                             });
    //                             rep_btn_container_ar2.children(".rep-add-spec-row, .rep-remove-spec-row").css({
    //                                 "width": "auto",
    //                                 "height": "auto",
    //                                 "padding": "0px",
    //                                 "margin": "auto 5px"
    //                             });
    //                             //adding event for original row button
    //                             evRepeaterAdd(rep_btn_container_ar2);
    //                             evRepeaterRemove(rep_btn_container_ar2);
    //                             // rebindFieldFunctionality(appended_row);
    //                             rebindFieldFunctionalityV3(appended_row);
    //                         }
    //                         // refreshRepeaterTable($(this).closest(".form-table"));
    //                         // rebindFieldFunctionality(appended_row); // MAY PROBLEMS PA SA NAMES BIND
    //                         // rebindFieldFunctionalityV2($(this).closest(".form-table"));

    //                         return false;
    //                     }
    //                 });
    //             }
    //         }
    //         function rebindFieldFunctionality(appended_row) { // defaultComputed(data_obj_id,the_field_ele,this_element,eventAddressNamespace){
    //             if (appended_row.find(".hasDatepicker").length >= 1) {
    //                 appended_row.find(".hasDatepicker").each(function() {
    //                     $(this).removeClass("hasDatepicker");
    //                     if ($(this).attr("data-type")) {
    //                         if ($(this).attr("data-type") == "date") {
    //                             $(this).datepicker({
    //                                 'dateFormat': 'yy-mm-dd'
    //                             });

    //                         } else if ($(this).attr("data-type") == "dateTime") {
    //                             $(this).datetimepicker({
    //                                 'dateFormat': 'yy-mm-dd'
    //                             });
    //                         }
    //                     }
    //                 });
    //             }
    //             appended_row.find(".setObject").each(function() {

    //             });
    //         }
    //         function rebindFieldFunctionalityV2(table) {
    //             var table_id = table.closest(".setOBJ").attr("data-object-id");
    //             table.find(".hasDatepicker").each(function(eqi) {
    //                 // console.log($(this).data())
    //                 // console.log(typeof $(this).data().datepicker);
    //                 //DESTROY HERE
    //                 if ($(this).data().datepicker) {
    //                     $(this).datepicker("destroy");
    //                 }
    //                 //REBIND HERE
    //                 if (typeof $(this).data().datepicker == "undefined") {
    //                     $(this).removeClass("hasDatepicker");
    //                     if ($(this).attr("data-type")) {
    //                         if ($(this).attr("data-type") == "date") {
    //                             $(this).datepicker({
    //                                 'dateFormat': 'yy-mm-dd'
    //                             });
    //                         } else if ($(this).attr("data-type") == "dateTime") {
    //                             $(this).datetimepicker({
    //                                 'dateFormat': 'yy-mm-dd'
    //                             });
    //                         }
    //                     }
    //                 }
    //             });
    //             // console.log("STARTING... REBINDING OF COMPUTED DEFAULT VALUE FIELDS LIST THEN");

    //             //destroy first
    //             $(".getFields").off("change.repeaterDefaultValueComputed" + table_id);
    //             $(".getFields").off("keyup.repeaterDefaultValueComputed" + table_id);
    //             //"startUpDefaultValComputed"
    //             //makeOnChange(fieldAffected,fieldWithComputation,eventAddressNamespace)
    //             table.children("tbody").children("tr").each(function(eqi_tr) {
    //                 $(this).find(".setOBJ").each(function(eqi_setOBJ) {
    //                     var obj_id = $(this).attr("data-object-id");
    //                     var this_setOBJFIELD = $(this).find(".getFields_" + obj_id);
    //                     // console.log("REFRESH")
    //                     // console.log(this_setOBJFIELD)
    //                     var this_setOBJFIELD_name = this_setOBJFIELD.eq(0).attr("name");
    //                     if (this_setOBJFIELD.data("events")) {
    //                         if (this_setOBJFIELD.data("events").change) {
    //                             for (var ctr = 0; ctr < this_setOBJFIELD.data("events").change.length; ctr++) {
    //                                 if (this_setOBJFIELD.data("events").change[ctr].namespace.toLowerCase().indexOf("startup") >= 0) {
    //                                     return true;
    //                                 }
    //                             }
    //                         }
    //                     }

    //                     if (this_setOBJFIELD.data("events")) {
    //                         if (this_setOBJFIELD.data("events").keyup) {
    //                             for (var ctr = 0; ctr < this_setOBJFIELD.data("events").keyup.length; ctr++) {
    //                                 if (this_setOBJFIELD.data("events").keyup[ctr].namespace.toLowerCase().indexOf("startup") >= 0) {
    //                                     return true;
    //                                 }
    //                             }
    //                         }
    //                     }

    //                     if (this_setOBJFIELD.attr("default-type")) { //PA ROW NORMAL lANG
    //                         if (this_setOBJFIELD.attr("default-type") == "computed") {
    //                             //REBIND DEFAULT VALUES COMPUTED
    //                             //console.log("REFRESh");
    //                             //console.log(this_setOBJFIELD);
    //                             defaultComputed(obj_id,this_setOBJFIELD,this,"repeaterDefaultValueComputed"+table_id);
    //                             // console.log( this_setOBJFIELD.parents(".setOBJ").eq(0) )
    //                         }
    //                     }
    //                     //console.log("arrgh")
    //                     //console.log(this_setOBJFIELD)
    //                     if (typeof this_setOBJFIELD.attr("event-id-from") != "undefined") { //PACOLUMN FORMULA IS AT OUTER @fieldName[sum]
    //                         var ids = this_setOBJFIELD.attr("event-id-from").split(",");
    //                         var idEleWithFormula = "";
    //                         for(var zz = 0 ; zz < ids.length ; zz++){
    //                             var idEleWithFormula = $(".getFields_" + ids[zz]);
    //                             makeOnChange(this_setOBJFIELD, idEleWithFormula, "repeaterDefaultValueComputed" + table_id);
    //                         }
    //                         // var idEleWithFormula = $(".getFields_" + this_setOBJFIELD.attr("event-id-from"));
    //                         // console.log("GEH NGA??")
    //                         // console.log(this_setOBJFIELD)
    //                         // makeOnChange(this_setOBJFIELD, idEleWithFormula, "repeaterDefaultValueComputed" + table_id);
    //                     }

    //                     //CURRENCY FORMAT
    //                     if(this_setOBJFIELD.attr("data-input-type") == 'Currency'){
    //                         var has_change_curr_format = false;
    //                         var data_events = this_setOBJFIELD.data("events");
    //                         if(typeof data_events != "undefined"){
    //                             if(typeof data_events["change"] != "undefined"){
    //                                 $.each(this_setOBJFIELD.data("events")["change"],function(index, value){
    //                                     if(value["namespace"] == "currency_format"){
    //                                         has_change_curr_format = true;
    //                                         return false;
    //                                     }
    //                                 });
    //                             }
    //                         }
    //                         if(has_change_curr_format == false){
    //                             this_setOBJFIELD.on("change.currency_format",function(){
    //                                 if($.isNumeric($(this).val())){
    //                                     var value_number = parseFloat($(this).val());
    //                                     $(this).val(value_number.currencyFormat());
    //                                 }else{
    //                                     var value_nito = $(this).val()
    //                                     var sanitized_val = value_nito.replace(/[\s,]/g,"");
    //                                     if($.isNumeric(sanitized_val)){
    //                                         var value_number = parseFloat(sanitized_val);
    //                                         $(this).val(value_number.currencyFormat());
    //                                     }
    //                                 }
    //                             });
    //                         }
    //                     }


    //                 });
    //             });
    //             table.find(".getFields").change();
    //         }

    //         function rebindFieldFunctionalityV3(appended_row){
    //             var select_tbody = $(appended_row).parents("tbody").eq(0);
    //             // var count_trs = select_tbody.children("tr").length;
    //             var count_trs = select_tbody.parents("table.form-table").data("added_rows_uid");
    //             var dis_appended_row = $(appended_row);
    //             var table_id = dis_appended_row.parents("table.form-table").eq(0).parents(".setOBJ").eq(0).attr("data-object-id");

    //             //remove class
    //             dis_appended_row.find(".hasDatepicker").removeClass("hasDatepicker");

    //             //remove attr's
    //             dis_appended_row.find("[value]").removeAttr("value");

    //             //fixing ids and names
    //             dis_appended_row.find("[data-object-id]").each(function(eq_name){//FIX IDS
    //                 if($(this).attr("rep-data-doi")){ //REPLACING THE GETFIELD UNIQUE CLASS
    //                     var doi = $(this).attr("rep-data-doi");
    //                     var getFields = $(this).find("*").filter(function(){
    //                         var regu_eks = new RegExp("getFields_"+doi,"g");
    //                         return regu_eks.test($(this).attr("rep-data-class"));
    //                     });

    //                     $(this).attr("data-object-id",$(this).attr("rep-data-doi")+"_UID"+count_trs);

    //                     if(getFields.attr("rep-data-class")){
    //                         var reg_eks = new RegExp("getFields_[0-9]*","g");
    //                         var replaced_class = getFields.attr("rep-data-class").replace(reg_eks, "getFields_"+doi+"_UID"+count_trs);
    //                         getFields.attr("class", replaced_class);
    //                     }
    //                 }else{ //REPLACING THE UNIQUE GETFIELD CLASS
    //                     $(this).attr("rep-data-doi",$(this).attr("data-object-id"));
    //                     $(this).attr("data-object-id",$(this).attr("data-object-id")+"_UID"+count_trs);
    //                     var new_doi = $(this).attr("rep-data-doi");
    //                     var getFields = $(this).find(".getFields_"+new_doi);
    //                     var reg_eks = new RegExp("getFields_[0-9]*","g");
    //                     getFields.attr("rep-data-class",getFields.attr("class"));
    //                     var replaced_class = getFields.attr("class").replace(reg_eks, "getFields_"+new_doi+"_UID"+count_trs);
    //                     getFields.attr("class", replaced_class);
    //                 }
    //             });

    //             dis_appended_row.find("[id]").each(function(eq_id){//FIX IDS
    //                 if($(this).attr("rep-data-id")){
    //                     $(this).attr("id",$(this).attr("rep-data-id")+"_UID"+count_trs);
    //                 }else{
    //                     $(this).attr("rep-data-id",$(this).attr("id"));
    //                     $(this).attr("id",$(this).attr("id")+"_UID"+count_trs);
    //                 }
    //             });
    //             dis_appended_row.find("[name]").each(function(eq_name){//FIX IDS
    //                 if($(this).attr("rep-original-name")){
    //                     $(this).attr("name",$(this).attr("rep-original-name")+"_UID"+count_trs);
    //                 }else{
    //                     $(this).attr("rep-original-name",$(this).attr("name"));
    //                     $(this).attr("name",$(this).attr("name")+"_UID"+count_trs);
    //                 }
    //             })




    //             //restoring functionality
    //             {
    //                 //DATEPICKER
    //                 dis_appended_row.find('input[data-type="date"]').each(function(eq_d){
    //                     $(this).datepicker({
    //                         'dateFormat': 'yy-mm-dd'
    //                     });
    //                     if(ThisDate($(this).val()) != "Invalid Date"){
    //                         $(this).val(ThisDate($(this).val()).formatDate("Y-m-d"));
    //                     }
    //                 })
    //                 //DATETIMEPICKER
    //                 dis_appended_row.find('input[data-type="dateTime"]').each(function(eq_d){
    //                     $(this).datetimepicker({
    //                         dateFormat: 'yy-mm-dd'
    //                     });
    //                     if(ThisDate($(this).val()) != "Invalid Date"){
    //                         $(this).val(ThisDate($(this).val()).formatDate("Y-m-d H:i"));
    //                     }
    //                 })
    //                 //TIME
    //                 dis_appended_row.find('input[data-type="time"]').each(function(eq_d){
    //                     $(this).datetimepicker({                   
    //                         dateFormat: '', 
    //                         timeFormat: 'HH:mm', 
    //                         timeOnly: true                                   
    //                     });
    //                     if(!$(this).val() && $(this).val().length >= 1){
    //                         var time_val = ThisDate(ThisDate(new Date()).formatDate("Y-m-d")+" "+$(this).val());

    //                         if(time_val != "Invalid Date"){
    //                             $(this).val(time_val.formatDate("H:i"));
    //                         }
    //                     }

    //                 })
    //                 //CURRENCY
    //                 dis_appended_row.find(".getFields[data-input-type='Currency']").each(function(){
    //                     $(this).on("change.currency_format",function(){
    //                         if($.isNumeric($(this).val())){
    //                             var value_number = parseFloat($(this).val());
    //                             $(this).val(value_number.currencyFormat());
    //                         }else{
    //                             var value_nito = $(this).val()
    //                             var sanitized_val = value_nito.replace(/[\s,]/g,"");
    //                             if($.isNumeric(sanitized_val)){
    //                                 var value_number = parseFloat(sanitized_val);
    //                                 $(this).val(value_number.currencyFormat());
    //                             }
    //                         }
    //                     })
    //                     $(this).change();
    //                 });
    //                 //REPEATER ACTION BUTTON DISABLING
    //                 dis_appended_row.on({
    //                     "mouseenter":function(e){
    //                         if(!$(this).find(".repeater-action").hasClass("disable-repeater-action")){
    //                             $(this).find(".repeater-action").css("display","");
    //                             $(this).find(".repeater-action").stop(false,false).animate({
    //                                 "opacity":1
    //                             },function(){
    //                                 //TEST
    //                             })
    //                         }
    //                     },
    //                     "mouseleave":function(e){
    //                         $(this).find(".repeater-action").stop(false,false).animate({
    //                             "opacity":0
    //                         },function(){
    //                             $(this).css("display","none");
    //                         })
    //                     }
    //                 })
    //                 {//DISABLING REPEATER ACTION BUTTON BASED OF DISABLED FIELDS
    //                     var total_field_disabled_in_row = dis_appended_row.find(".getFields:disabled").length;
    //                     var total_field_in_row = dis_appended_row.find(".getFields").length;
    //                     if(total_field_disabled_in_row == total_field_in_row){
    //                         dis_appended_row.find(".repeater-action").addClass("disable-repeater-action");
    //                     }
    //                 }
    //                 //REBIND DEFAILT COMPUTED
    //                 dis_appended_row.find('.getFields[default-type="computed"][default-formula-value]').each(function(){
    //                     console.log("ELEMENT REPEATED W FORMULAS "+$(this).attr("name"), $(this));
    //                     var this_element_setOBJ = $(this).parents(".setOBJ").eq(0);
    //                     var this_element_field = $(this);
    //                     var data_obj_id = this_element_setOBJ.attr("data-object-id");

    //                     self_ini.defaultComputed(data_obj_id, this_element_field, this_element_setOBJ, "repeaterDefaultValueComputed"+table_id);
    //                 });
    //                 //REBIND FIELDS FROM COMPUTED FORMULAS
    //                 dis_appended_row.find('.getFields[event-id-from]').each(function(eqi){

    //                     var edoi_from = $(this).attr("event-id-from"); 
    //                     var element_in_computation = $(this);
    //                     var splitted_edoi_from = edoi_from.split(",");

    //                     for(index_oid in splitted_edoi_from){

    //                         var the_fields = $("[data-object-id='"+splitted_edoi_from[index_oid]+"']").find(".getFields_"+splitted_edoi_from[index_oid]);
    //                         if(the_fields.attr("default-formula-value")){
    //                             console.log("ID MAY FORMULA"+splitted_edoi_from[index_oid],the_fields.attr("name"), element_in_computation.attr("name"), "TBL ID::"+table_id)
    //                             var eventAddressNamespace = "repeaterDefaultValueComputed" + table_id;
    //                             self_ini.makeOnChange(element_in_computation, the_fields, eventAddressNamespace);
    //                         }
    //                     }

    //                 })
    //                 //TRIGGER CHANGES OF NEWLY ADDED ROW
    //                 dis_appended_row.find('.getFields').filter(function(index, element){
    //                     var dis_ele = $(element);
    //                     var dis_ele_ev_data = dis_ele.data("events")
    //                     if(dis_ele_ev_data){
    //                         if(dis_ele_ev_data["change"]){
    //                             if(dis_ele_ev_data["change"].length >= 1){
    //                                 return true;
    //                             }
    //                         }
    //                     }
    //                 }).change();
    //             }
    //         }

    //         function evRepeaterRemove(repeaterBtnEle) {
    //             if (repeaterBtnEle.children(".rep-remove-spec-row").length >= 1) {
    //                 repeaterBtnEle.children(".rep-remove-spec-row").on({
    //                     "click": function(e) {
    //                         e.preventDefault();
    //                         if ($(this).attr("disabled")) {

    //                         } else {
    //                             $(this).closest("tr").children("td").animate({
    //                                 "height": 0
    //                             }, function() {
    //                                 var this_table = $(this).closest(".form-table");
    //                                 $(this).closest("tr").remove();
    //                                 this_table.find("tbody").eq(0).children("tr").eq(0).find(".getFields").filter(function(index, dom){ //UNANG ROW LANG ANG NAKA .CHANGE
    //                                     var dis_ele_dom = $(this)
    //                                     var ded_data_events = dis_ele_dom.data("events");
    //                                     if(ded_data_events["change"]){
    //                                         if(ded_data_events["change"].length >= 1){
    //                                             return true;
    //                                         }
    //                                     }
    //                                     return false;
    //                                 }).change();
    //                                 // refreshRepeaterTable(this_table);
    //                                 // rebindFieldFunctionalityV2(this_table);
    //                             });
    //                         }
    //                         return false;
    //                     }
    //                 });
    //             }
    //         }
    //         function refreshRepeaterTable(tableEle) {
    //             var field_container = ".setOBJ";
    //             var table_body = $(tableEle).children("tbody");
    //             var table_row = table_body.children("tr");
    //             $(table_row).each(function(eqi_tr_i) {
    //                 var total_field_disabled_in_row = $(this).find(".getFields:disabled").length;
    //                 var total_field_in_row = $(this).find(".getFields").length;
    //                 if (total_field_in_row == total_field_disabled_in_row) {
    //                     $(this).find(".repeater-action").css("opacity", 0);
    //                     $(this).find(".repeater-action").addClass("disable-repeater-action");
    //                     $(".disable-repeater-action").children(".rep-remove-spec-row,.rep-add-spec-row").attr("disabled", true);
    //                     $(".disable-repeater-action").children(".rep-remove-spec-row,.rep-add-spec-row").prop("disabled", true);
    //                 }
    //                 if ($(this).hasClass("original-row")) {
    //                     //
    //                 } else {
    //                     $(this).find(field_container).each(function() {
    //                         sobj_index_id = $(this).attr("data-object-id");
    //                         $(this).find(".getFields_" + sobj_index_id).each(function() {

    //                             if (!$(this).attr("rep-original-id")) {
    //                                 $(this).attr("rep-original-id", $(this).attr("id"));
    //                                 $(this).attr("id", $(this).attr("rep-original-id") + "_tr" + eqi_tr_i);
    //                             } else {
    //                                 //
    //                                 $(this).attr("id", $(this).attr("rep-original-id") + "_tr" + eqi_tr_i);
    //                             }

    //                             if (!$(this).attr("rep-original-name")) {
    //                                 $(this).attr("rep-original-name", $(this).attr("name"));
    //                                 $(this).attr("name", $(this).attr("rep-original-name") + "_tr" + eqi_tr_i);
    //                             } else {
    //                                 //
    //                                 $(this).attr("name", $(this).attr("rep-original-name") + "_tr" + eqi_tr_i);
    //                             }

    //                             //MAKE AN INDEX TOO ON FORMULAS
    //                             // if($(this).attr("default-type")){
    //                             //    if($(this).attr("default-type") == "computed"){
    //                             //      var computed_default_value = $(this).attr("default-formula-value");
    //                             //      var splitted_default_val = computed_default_value.match(/@\(.*?\)|@[a-zA-Z0-9_]*/g);
    //                             //      if(splitted_default_val != null){
    //                             //            console.log("FIGURE THIS OUT")
    //                             //            for(var ctr = 0 ; ctr < splitted_default_val.length ; ctr++){
    //                             //                  var formula_key_words = new Array("@Department","@Status","@Requestor","@RequestID","@Now","@Today","@TrackNo","@CurrentUser","@StrRight","@StrLeft","@GivenIf");
    //                             //                  var ele_in_formula = $('[name="'+splitted_default_val[ctr].replace("@","")+'"]');
    //                             //                  if(ele_in_formula.length >= 1){
    //                             //                        console.log(ele_in_formula.data("events"));
    //                             //                        var ele_in_f_val = $.trim(ele_in_formula.val() );
    //                             //                        if($.isNumeric(ele_in_f_val ) ){
    //                             //                             computed_default_value = computed_default_value.replace(splitted_default_val[ctr], ele_in_f_val);
    //                             //                        }else{
    //                             //                             computed_default_value = computed_default_value.replace(splitted_default_val[ctr], "\""+ele_in_f_val+"\"");
    //                             //                        }
    //                             //                  }else{
    //                             //                         if(formula_key_words.indexOf(splitted_default_val[ctr]) >= 0 ){
    //                             //                            if(splitted_default_val[ctr] == "@Requestor"){
    //                             //                                 requestor_ele = "<?php echo $auth['display_name']; ?>";
    //                             //                                 computed_default_value = computed_default_value.replace(splitted_default_val[ctr],"\""+requestor_ele+"\"" );
    //                             //                            }else if(splitted_default_val[ctr] == "@RequestID"){
    //                             //                                 var value_reqID = $("#ID").val();
    //                             //                                 computed_default_value = computed_default_value.replace(splitted_default_val[ctr], value_reqID);
    //                             //                            }else if(splitted_default_val[ctr] == "@Department"){
    //                             //                                 var value_reqID = $("[name='Department_Name']").val();
    //                             //                                 computed_default_value = computed_default_value.replace(splitted_default_val[ctr], value_reqID);
    //                             //                            }else if(splitted_default_val[ctr] == "@RowIndex"){

    //                             //                                 if($(this).parents("tr").length >=1){
    //                             //                                     var rowIndex_val = $(this).parents("tr").eq(0).index();
    //                             //                                     computed_default_value = computed_default_value.replace(splitted_default_val[ctr], rowIndex_val);
    //                             //                                 }
    //                             //                            }
    //                             //                            continue;
    //                             //                          }else{
    //                             //                            var toBeReplace = splitted_default_val[ctr];
    //                             //                            var formula_RegExp = new RegExp("("+toBeReplace+"|"+toBeReplace+"_tr[0-9]*)","g");
    //                             //                            computed_default_value = computed_default_value.replace(formula_RegExp, splitted_default_val[ctr].replace(/_tr[0-9]*/g,"")+"_tr"+eqi_tr_i);
    //                             //                          }
    //                             //                  }
    //                             //            }
    //                             //      }
    //                             //      var status_ok = "false";
    //                             //      try{
    //                             //         eval(computed_default_value);
    //                             //         status_ok = "true";
    //                             //      }catch(eerr){

    //                             //      }
    //                             //      if(status_ok== "true"){
    //                             //         $(this).val(eval(computed_default_value));
    //                             //      }
    //                             //    }
    //                             // }
    //                         });

    //                         $(this).find(".pickListButton").each(function() {
    //                             if (!$(this).attr("original-return-field")) {
    //                                 $(this).attr("original-return-field", $(this).attr("return-field"));
    //                                 $(this).attr("return-field", $(this).attr("original-return-field") + "_tr" + eqi_tr_i);
    //                             } else {
    //                                 $(this).attr("return-field", $(this).attr("original-return-field") + "_tr" + eqi_tr_i);
    //                             }
    //                         });
    //                     });
    //                 }
    //             });
    //             if (typeof callBack != "undefined") {
    //                 callBack(tableEle);
    //             }
    //         }

    //         refreshRepeaterTable(tableElement); // this excute at the startup of repeater table ... so that the rows with no fields 
    //     }



    //     // {//eyAH NEW VERSION REPEATER TABLE FAST
    //     //     function evRepeaterAddV2(row_button){
    //     //         if (row_button.find(".rep-add-spec-row").length >= 1) {
    //     //             row_button.find(".rep-add-spec-row").eq(0).on("click",function(){
    //     //                 var tr_element = $(this).parents("tr").eq(0);
    //     //                 var tr_append_location = tr_element;
    //     //                 var tr_cloned = tr_element.clone();
    //     //                 tr_append_location.after(tr_cloned);
    //     //                 tr_cloned.find(".rep-remove-spec-row").css("display","");
    //     //             })
    //     //         }
    //     //     }
    //     //     function evRepeaterRemoveV2(row_button){
    //     //         if (row_button.find(".rep-remove-spec-row").length >= 1) {
    //     //             row_button.find(".rep-remove-spec-row").eq(0).on("click",function(){
    //     //                 alert("MAYNUS");
    //     //             })
    //     //         }
    //     //     }
    //     // }

    //     if (typeof callBack != "undefined") {
    //         callBack(tableElement);
    //     }
    // },
}